Built-in functions (e.g. isFinite) type guard and accepting null | undefined (strictNullChecks)
See original GitHub issueTypeScript Version: 2.0.0
Code
// --strictNullChecks
interface IExample {
value?: number;
}
let example: IExample = {};
if (isFinite(example.value)) { // Accept possibly `undefined`
let a = example.value; // Narrow to `number`
}
Expected behavior:
- isFinite should accept
number | null | undefined
rather than strictlynumber
. - isFinite should act as a type guard.
Actual behavior:
Won’t compile because isFinite
is not accepting undefined
and is not a type guard.
Proposal:
Change:
declare function isFinite(number: number): boolean;
To:
declare function isFinite(number: number | null | undefined): number is number;
I’m pretty sure there are other functions that could use the same love. I don’t mind putting in some hours if this is an accepted direction to take. Let me know 😃
Issue Analytics
- State:
- Created 7 years ago
- Reactions:7
- Comments:20 (6 by maintainers)
Top Results From Across the Web
strictNullChecks - TSConfig Option - TypeScript
When strictNullChecks is true , null and undefined have their own distinct types and you'll get a type error if you try to...
Read more >Why Number.isFinite dont have type guard? - Stack Overflow
isFinite dont have type guard like number is number ? THis example provides an error Object is possibly 'undefined' function inc (n?: number)...
Read more >TypeScript - Type Guards For null and undefined - LogicBig
As we saw in Data types tutorial, TypeScript has two special types, null and undefined. These two types can have the values 'null'...
Read more >https://raw.githubusercontent.com/microsoft/TypeSc...
TypeofNEFunction }); type TypeSystemEntity = Node | Symbol | Type ... for public members that accept a Node or one of its subtypes,...
Read more >This copy of the TypeScript handbook was created on Monday ...
strictNullChecks. By default, values like null and undefined are assignable to any other type. This can make writing some code easier, but forgetting...
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
JavaScript (╯°□°)╯︵ ┻━┻
It’s probably best to not allow
null
, then?As far as I can understand this issue, my recent troubles with this issue, the current implementation of TypeScript (4.5.4), and the specifications of ECMAScript on the matter, both typings are wrong and should look something more like:
isFinite
:NumberConstructor.isFinite
: