Skip to content

Bad type checking inside typeguarded block #32625

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

Closed
lonewarrior556 opened this issue Jul 30, 2019 · 4 comments · Fixed by #56908
Closed

Bad type checking inside typeguarded block #32625

lonewarrior556 opened this issue Jul 30, 2019 · 4 comments · Fixed by #56908
Labels
Duplicate An existing issue was already created

Comments

@lonewarrior556
Copy link

lonewarrior556 commented Jul 30, 2019

TypeScript Version: 3.5.1

Search Terms: Type Guard

interface FOO {
    [key:string]: number
}

declare var foo: FOO | null

if(foo) {
    var a =  foo['string'] // good
    Object.keys(foo).map(key => {
        var b =  foo[key]  // foo cannot possibly be null
    })
}

//related
foo && foo['string'] && Object.keys(foo).map(key => {
    var a = foo[key] // foo cannot possibly be null
})

Expected behavior:
Should know Object is not 'null'

Actual behavior:
Thinks Object is possibly 'null'

Playground Link: ts-playground

Related Issues:

@AnyhowStep
Copy link
Contributor

It cannot know that foo won't become null inside the function, in the general case.

In this specific instance, you can say that the callback is invoked immediately and never invoked again after .map(), so, it cannot be null.

But the compiler can't know that for sure yet

@AnyhowStep
Copy link
Contributor

#11498

@fatcerberus
Copy link

Also see #9998.

@RyanCavanaugh RyanCavanaugh added the Duplicate An existing issue was already created label Jul 30, 2019
@typescript-bot
Copy link
Collaborator

This issue has been marked as a 'Duplicate' and has seen no recent activity. It has been automatically closed for house-keeping purposes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Duplicate An existing issue was already created
Projects
None yet
Development

Successfully merging a pull request may close this issue.

5 participants