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

narrowing doesn't work #11433

Closed
zpdDG4gta8XKpMCd opened this issue Oct 6, 2016 · 3 comments
Closed

narrowing doesn't work #11433

zpdDG4gta8XKpMCd opened this issue Oct 6, 2016 · 3 comments
Assignees
Labels
Bug A bug in TypeScript

Comments

@zpdDG4gta8XKpMCd
Copy link

zpdDG4gta8XKpMCd commented Oct 6, 2016

latest nightly build as of October 6, 2016:

interface A { kind: 'A'; a: number; }
interface B { kind: 'B'; b: number; }
type AB = A | B;
export function toResult<Z extends { kind: K; }, K extends string>(
    value: AB | Z,
    orElse: (value: Z) => number
): number {
    switch (value.kind) {
        case 'A': return value.a; // <-- problem, value isn't narrowed to A
        case 'B': return value.b;
        default: return orElse(value);
    }
}
@zpdDG4gta8XKpMCd
Copy link
Author

despite #10417 (comment)

@mhegazy mhegazy added the Bug A bug in TypeScript label Oct 10, 2016
@mhegazy mhegazy added this to the Future milestone Oct 10, 2016
@ahejlsberg
Copy link
Member

I don't think this is a bug. We don't know for sure that Z's kind property isn't 'A' or 'B' (it could basically be any string value), so we can't safely narrow to A or B in the switch cases.

@zpdDG4gta8XKpMCd
Copy link
Author

zpdDG4gta8XKpMCd commented Oct 13, 2016

i see your point, negating type constraints (#7993) could have guaranteed that Z.kind is neither A nor B:

export function toResult<Z extends { kind: K; }, K extends string unlike 'A', 'B'>(

@mhegazy mhegazy removed this from the Future milestone Apr 26, 2018
@microsoft microsoft locked and limited conversation to collaborators Jul 31, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Bug A bug in TypeScript
Projects
None yet
Development

No branches or pull requests

4 participants