TypeScript: Built-in functions (e.g. isFinite) type guard and accepting null | undefined (strictNullChecks)
TypeScript 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 | undefinedrather 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 😃
About this issue
- Original URL
- State: closed
- Created 8 years ago
- Reactions: 9
- Comments: 22 (8 by maintainers)
Commits related to this issue
- #10038 fix types in d.ts definitions — committed to pladaria/TypeScript by deleted user 10 months ago
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:this can definitely be improved. for example when doing:
typescript warns me about the
xin the assert thatObject is possibly 'undefined'. butxcannot possibly beundefinedin this case.JavaScript (╯°□°)╯︵ ┻━┻
It’s probably best to not allow
null, then?isFinite(null)actually returns true (null gets coerced to 0)It would also be useful if it returned a type predicate.