Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closure error TS2532 #21162

Closed
ghost opened this issue Jan 12, 2018 · 1 comment
Closed

Closure error TS2532 #21162

ghost opened this issue Jan 12, 2018 · 1 comment
Labels
Working as Intended The behavior described is the intended behavior; this is not a bug

Comments

@ghost
Copy link

ghost commented Jan 12, 2018

TypeScript Version: 2.6.2 | 2.7.0-dev.20180112

Code

// test.ts
function foo(map: Map<string, string>) {
    let bar = map.get('key');
    if (!bar) {
        return;
    }

    let res1 = bar.repeat(3);

    let fun = () => {
        let res2 = bar.repeat(3);
    }
}

Expected behavior:
no errors

Actual behavior:
test.ts(11,20): error TS2532: Object is possibly 'undefined'.

@ahejlsberg
Copy link
Member

This is working as intended. Type guards remain in effect across function boundaries only when the guarded variable(s) are considered constant. This is the case for const local variables and parameters that never occur as assignment targets in the function, so if you declare bar using const it works as you expect. See #10357.

@ahejlsberg ahejlsberg added the Working as Intended The behavior described is the intended behavior; this is not a bug label Jan 12, 2018
@microsoft microsoft locked and limited conversation to collaborators Jul 3, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Working as Intended The behavior described is the intended behavior; this is not a bug
Projects
None yet
Development

No branches or pull requests

2 participants