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

Lookup types do not work well with type guards #12805

Closed
panhania opened this issue Dec 9, 2016 · 3 comments
Closed

Lookup types do not work well with type guards #12805

panhania opened this issue Dec 9, 2016 · 3 comments
Labels
Duplicate An existing issue was already created

Comments

@panhania
Copy link

panhania commented Dec 9, 2016

TypeScript Version: 2.1.4

Consider this simple property getter function (defined in What's New of TypeScript 2.1):

function prop<T, K extends keyof T>(obj: T, key: K): T[K] {
    return obj[key];
}

I would expect that prop(foo, "bar") works the same way foo.bar does. However, if the type of the property is narrowed using type guards, the prop function stops working as expected:

interface Foo {
    bar?: number;
}

function quux(foo: Foo) {
    if (foo.bar) {
        let baz: number = prop(foo, "bar"); // error TS2322: Type 'number | undefined' is not assignable to type 'number'.
    }
}

Expected behavior: The code should compile just fine.
Actual behavior: Compilation ends with a type error.

@RyanCavanaugh
Copy link
Member

Tentatively a duplicate of #10065 - type guards affect properties, but don't synthesize the kinds of on-the-fly new types that would be required to identify this in the general case. But here we should be ending up at the same symbol and resolving this correctly

@RyanCavanaugh
Copy link
Member

@ahejlsberg any cheap fix possible?

@ahejlsberg
Copy link
Member

@RyanCavanaugh Nothing cheap comes to mind. The real fix would be to address the issue in #10065 (which would fix several other issues as well).

@RyanCavanaugh RyanCavanaugh added the Duplicate An existing issue was already created label Dec 12, 2016
@microsoft microsoft locked and limited conversation to collaborators Jun 19, 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