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

Wrong type narrowing to 'never' after 'in' #21714

Closed
JanKoehnlein opened this issue Feb 7, 2018 · 3 comments
Closed

Wrong type narrowing to 'never' after 'in' #21714

JanKoehnlein opened this issue Feb 7, 2018 · 3 comments
Labels
Duplicate An existing issue was already created

Comments

@JanKoehnlein
Copy link

Search Terms:
Type narrowing, 'in'

Code

interface Foo { 
    foo: boolean
}

interface Bar {
    bar: boolean
}

function isFooAndHasBar(foo: Foo): foo is Foo & Bar {
    return 'bar' in foo && foo.foo; 
}

Expected behavior:
No type error. Just because there is an additional property in a Foo, it should still have all props of Foo.

Actual behavior:
Error: Property 'foo' does not exist on type 'never'

Playground Link:
https://www.typescriptlang.org/play/index.html#src=interface%20Foo%20%7B%20%0D%0A%20%20%20%20foo%3A%20boolean%0D%0A%7D%0D%0A%0D%0Ainterface%20Bar%20%7B%0D%0A%20%20%20%20bar%3A%20boolean%0D%0A%7D%0D%0A%0D%0Afunction%20isFooAndHasBar(foo%3A%20Foo)%3A%20foo%20is%20Foo%20%26%20Bar%20%7B%0D%0A%20%20%20%20return%20'bar'%20in%20foo%20%26%26%20foo.foo%3B%0D%0A%7D

Related Issues:
#20583
Note that this is about the true branch (&&), and that foo itself is narrowed down to never (not foo.foo).
Current workaround: Switch operands. Had to do this in quite a few places in my codebase.

JanKoehnlein added a commit to theia-ide/sprotty that referenced this issue Feb 7, 2018
@niieani
Copy link

niieani commented Feb 7, 2018

You are expecting foo of type Foo as the parameter. You need to use a generic and expect something that extends Foo:

function isFooAndHasBar<T extends Foo>(foo: T): foo is Foo & Bar {
    return 'bar' in foo && foo.foo;
}

Playground

@mhegazy mhegazy added the Duplicate An existing issue was already created label Feb 7, 2018
@mhegazy
Copy link
Contributor

mhegazy commented Feb 7, 2018

duplicate of #21517.

@typescript-bot
Copy link
Collaborator

Automatically closing this issue for housekeeping purposes. The issue labels indicate that it is unactionable at the moment or has already been addressed.

@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
Duplicate An existing issue was already created
Projects
None yet
Development

No branches or pull requests

4 participants