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 type via Function Assertion loses numeric type #37807

Closed
eyedean opened this issue Apr 6, 2020 · 3 comments · Fixed by #49625
Closed

Narrowing type via Function Assertion loses numeric type #37807

eyedean opened this issue Apr 6, 2020 · 3 comments · Fixed by #49625

Comments

@eyedean
Copy link

eyedean commented Apr 6, 2020

TypeScript Version: 3.9.0-dev.20200406

Search Terms: assertion, function, narrowing, numeric types

Code

// GOOD EXAMPLE
function f1(x: any): asserts x is number | undefined { }
let v1: number | string | undefined;
f1(v1)
type t1 = typeof v1; // t1 = number | undefined, as excepted

// BUGGY EXAMPLE
function f2(x: any): asserts x is 6 | undefined { }
let v2: number | string | undefined;
f2(v2)
type t2 = typeof v2; // t2 = undefined.  Expected to be 6 | undefined

Expected behavior: t2 must be 6 | undefined.

Actual behavior: t2 is undefined only.

Playground Link: Playground Link

Related Issues: I went through the comments of the popular #32695 by @ahejlsberg and also searched in the existing issues but couldn't find any similar problem being reported in the past.

FWIW, I ran into this trying to write a assertIsInEnumValues for Numeric Enums. (related StackOverflow question: https://stackoverflow.com/a/61058457)

@jack-williams
Copy link
Collaborator

I think this is a duplicate of #31156

@eyedean
Copy link
Author

eyedean commented Apr 6, 2020

@jack-williams thanks for commenting. It's definitely not limited to undefined (I just tested and it has the same bug with boolean as well). However, I can definitely smell that "branded primitives" discussed at #31206 might have caused it.

@sandersn
Copy link
Member

sandersn commented Apr 7, 2020

Yep, it's a duplicate of #31156 -- the unions on the source and target are the cause. Swapping undefined for boolean has the same problem.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
3 participants