Typescript: Number methods should support type guards

Created on 16 Oct 2016  路  8Comments  路  Source: microsoft/TypeScript

Most helpful comment

i really like it! (suggestion! accepting prs!)

so what exactly is an integer number as far as the TypeScript types go?

function isInteger(value: number): value is number & .....? { // <--- replace .....? with something meaningful
}

All 8 comments

This sounds like a good idea. One minor correction, these are not methods of Number.prototype but rather of the Number function.

PRs welcomed. You can find more information about contributing lib.d.ts fixes at https://github.com/Microsoft/TypeScript/blob/master/CONTRIBUTING.md#contributing-libdts-fixes.

i really like it! (suggestion! accepting prs!)

so what exactly is an integer number as far as the TypeScript types go?

function isInteger(value: number): value is number & .....? { // <--- replace .....? with something meaningful
}

you would only use number. the argument should allow non-numeric types as well.

declare function isInteger(value: any): value is number ;

oh, nevermind then

@aleksey-bykov still a good question. Maybe in the future TypeScript's type system will be so advanced that it will be able to infer discrete vs continuous types O.O

This turns out to be a bad idea because type guards need to return true for all of the values in the domain of their guarded type, not just some of them. In other words, with the proposed definition:

let x: number | string = ...;
if (typeof x === 'string') {

} else if (isInteger(x)) {
  // x: number
} else {
  // We assume 'x: never' in this block!
  // error
  console.log(x.toFixed(2));
}

I see. That is definitely a problem. This really did seem like a good idea but I guess I didn't really think it through.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

xealot picture xealot  路  150Comments

tenry92 picture tenry92  路  146Comments

nitzantomer picture nitzantomer  路  135Comments

sandersn picture sandersn  路  265Comments

jonathandturner picture jonathandturner  路  147Comments