-
Notifications
You must be signed in to change notification settings - Fork 12.8k
Infer parameter as number when using Number.is* #44664
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
Conversation
When using the `Number.is*` (`Number.isFinite`, `Number.isInteger`, `Number.isNaN` and `Number.isSafeInteger`), the parameter's type should be inferred as `number`. Example: ```typescript function foo(value?: number) { if (Number.isFinite(value)) { bar(value) } } function bar (value: number) { ... } ```
This PR doesn't have any linked issues. Please open an issue that references this PR. From there we can discuss and prioritise. |
The reason this isn't the case is because: function isFinite(x: unknown): x is number
{
return Number.isFinite(x);
}
let foo: number | string = Infinity as number | string;
if (!isFinite(foo)) {
foo; // string?!
} Type predicates work in both directions. |
@fatcerberus: This would be true for the global See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite
Example: console.log(Number.isFinite('12')) // false |
@til-schneider Notice the negation operator before. And see #39090 (comment). |
OK, I see. That's unfortunate... So the only correct inference would be |
No, this does't work either. Only |
That would be the case if |
@til-schneider Notice that I wasn’t using the built-in global |
When using the
Number.is*
(Number.isFinite
,Number.isInteger
,Number.isNaN
andNumber.isSafeInteger
), the parameter's type should be inferred asnumber
.Example: