Skip to content

NaN incorrectly narrows to 0 #36964

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

Open
osyrisrblx opened this issue Feb 23, 2020 · 4 comments
Open

NaN incorrectly narrows to 0 #36964

osyrisrblx opened this issue Feb 23, 2020 · 4 comments
Labels
Awaiting More Feedback This means we'd like to hear from more people who would be helped by this feature Suggestion An idea for TypeScript

Comments

@osyrisrblx
Copy link

osyrisrblx commented Feb 23, 2020

TypeScript Version: 3.9.0-dev.20200222

Search Terms: NaN Truthiness Falsy

Code

function bool(): boolean { return false; }
function number(): number { return NaN; }

let a = number();
let b = bool();

const x = a && b; // type = boolean | 0
console.log(x); // prints NaN (which is neither boolean, nor 0)

Expected behavior:
Type of x should be number | boolean.

Since NaN isn't a "unit type" like 0, we can't express NaN without using number.

Actual behavior:
Type of x is 0 | boolean.

Playground Link: playground link

Related Issues:
#32778 (Incorrectly marked as duplicate?)

@RyanCavanaugh RyanCavanaugh added Awaiting More Feedback This means we'd like to hear from more people who would be helped by this feature Suggestion An idea for TypeScript labels Feb 24, 2020
@RyanCavanaugh
Copy link
Member

See also #32277 - would need a NaN type to represent this

@RyanCavanaugh RyanCavanaugh changed the title NaN is not considered falsy Add NaN literal type Feb 24, 2020
@jcalz
Copy link
Contributor

jcalz commented Feb 24, 2020

Looks like people might be slightly talking past each other here. Soundness would require that a number which has been determined to be falsy should be narrowed to type 0 | typeof NaN.

So either:

@osyrisrblx
Copy link
Author

• Falsy checks on number shouldn't narrow at all since 0 | typeof NaN is just number . That seems to be what this issue is specifically asking for.

Exactly this. If we can't have NaN as a type, then it shouldn't narrow for number.

I'd also say this isn't a "suggestion", but a soundness/type safety bug!

@zacnomore
Copy link

May I politely suggest changing the title to "NaN incorrectly narrows to 0" or something similar? I
think it would help ensure that this is correctly identified as a bug .

@osyrisrblx osyrisrblx changed the title NaN is not recognized as falsy. NaN incorrectly narrows to 0 Aug 27, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Awaiting More Feedback This means we'd like to hear from more people who would be helped by this feature Suggestion An idea for TypeScript
Projects
None yet
Development

No branches or pull requests

4 participants