Skip to content

typeof switch filters union types but does not narrow them #27335

New issue

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

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

Already on GitHub? # to your account

Closed
jack-williams opened this issue Sep 25, 2018 · 5 comments · Fixed by #27680
Closed

typeof switch filters union types but does not narrow them #27335

jack-williams opened this issue Sep 25, 2018 · 5 comments · Fixed by #27680
Assignees
Labels
Bug A bug in TypeScript Fixed A PR has been merged for this issue

Comments

@jack-williams
Copy link
Collaborator

TypeScript Version: 83fe1ea

Search Terms: switch typeof narrowing narrows

Code

// @strictNullChecks: true
function narrowingNarrows(x: {} | undefined) {
    switch (typeof x) {
        case 'string': x; return; // x is {}, should be string
        case 'number': x; return; // x is {}, should be number
    } 
}

Expected behavior:

Switching on typeof should narrow union members in addition to filtering.

  • In the first clause, undefined should be filtered and {} should be narrowed to string.
  • In the second clause, undefined should be filtered and {} should be narrowed to number.

Actual behavior:

Switching on typeof only filters unions.

  • In the first clause, undefined is filtered but {} is not narrowed.
  • In the second clause, undefined is filtered but {} is not narrowed.

Playground Link: Link: N/A (Playground not on this version).

@ghost ghost added Bug A bug in TypeScript Fixed A PR has been merged for this issue labels Sep 25, 2018
@jack-williams
Copy link
Collaborator Author

Should this have a fixed label or should it wait on merging a PR?

@weswigham
Copy link
Member

weswigham commented Sep 25, 2018

The PR's in a milestone (even if not yet merged), so the fixed label is fine. It's good for making sure nobody else picks up the issue accidentally while it's still open.

@jack-williams
Copy link
Collaborator Author

jack-williams commented Sep 26, 2018

Cheers @weswigham. Might be worth adding a fixed label to #27180 as it is handled by the same PR.

@RyanCavanaugh
Copy link
Member

@weswigham assigning to you for tracking purposes

@jack-williams
Copy link
Collaborator Author

@RyanCavanaugh @weswigham

Is there any merit in trying to unify the if and switch narrowing code under typeof, at least to some degree?

# for free to join this conversation on GitHub. Already have an account? # to comment
Labels
Bug A bug in TypeScript Fixed A PR has been merged for this issue
Projects
None yet
3 participants