Skip to content

Unable to include a literal NaN, Infinity, or -Infinity in a union type #47347

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

Closed
ljharb opened this issue Jan 7, 2022 · 5 comments
Closed
Labels
Duplicate An existing issue was already created

Comments

@ljharb
Copy link
Contributor

ljharb commented Jan 7, 2022

Bug Report

See the link below. I want to define a function as returning either NaN, 1, 2, or 3. I can do 1 | 2 | 3, but TS errors when I do NaN | 1 | 2 | 3, and if i do typeof NaN it allows any number.

⏯ Playground Link

Playground link with relevant code

💻 Code

const a: () => typeof NaN | 1 = () => NaN; // explicitly allows any number
const x: number = a(); // should pass, does

const b: () => 1 | 2 = () => 1; // works fine
const y: 1 = b(); // fails, as it should

const c: () => NaN | Infinity | -Infinity | 1 = () => NaN; // errors, but shouldn't
const z: 1 = c(); // should not pass, but does

🙁 Actual behavior

The c declaration errors, and the z assignment does not fail.

🙂 Expected behavior

The c declaration works, and the z assignment should fail. Why? Because NaN and the Infinities are just as much a number as 1 and 2 are, and I want to correctly type my API.

@fatcerberus
Copy link

Note #9407 (comment) - this was apparently a deliberate choice.

@ljharb
Copy link
Contributor Author

ljharb commented Jan 7, 2022

My compelling scenario is that npm's lockfileVersion can be 1, 2, or 3, but my API (before I tried to add typings to it) returned NaN when it can't detect the version being used.

@MartinJohns
Copy link
Contributor

MartinJohns commented Jan 7, 2022

Duplicate of #15135. Definitely not a bug.

edit: No idea why you decide to downvote my comment, when I'm just pointing you to the decision of the team.

@ljharb
Copy link
Contributor Author

ljharb commented Jan 7, 2022

@MartinJohns thanks for the pointer :-) the downvote was for the decision.

@typescript-bot
Copy link
Collaborator

This issue has been marked as a 'Duplicate' and has seen no recent activity. It has been automatically closed for house-keeping purposes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Duplicate An existing issue was already created
Projects
None yet
Development

No branches or pull requests

5 participants