Why does TypeScript not throw a type missmatch in the following?
undefined * 1 === NaN
Implementing a type-check for it would be trivial:
(n : number, m : number) => number
Would it also be possible to implement one for the + operator?
Typescript is defined as a superset of JavaScript. Restricting that operation would forbid using otherwise valid JS code in TS.
Sure, but personally I'd want TypeScipt to try to prevent me from ever producing NaN
NaN is kind of a special case, because while "not a number" in the name, it still lies in the domain of the Number type (mostly because of underlying IEEE-754 implementation). Either way, you can construct your own stricter types (e.g. wrapping Number) if you need/want that.
You can't really safe guard against getting a NaN value based on the compiler, here's an example:
function mul(x: number, y: number): number {
return x * y;
}
function getDataFromServer(): Promise<number> {
// async request which returns a number
}
getDataFromServer().then(num => mul(num, 2));
The compiler has no way of knowing what the server will return.
It might be a number, it might be a string representation of a number ("2"), it might even be "internal server error".
You can check for those things at runtime in your code, but the compiler can't figure that statically.
getDataFromServer needs to guarantee that whatever server returned either forms a number, or signal promise error. That's how the compiler figures that statically. It has nothing to do with the OP asking about numerical operators not having stricter signatures.getDataFromServer that it returns a number, but I was trying to show that the compiler can't possibly know whether it will be a number, NaN or something else."undefined * 1 is a valid javascript statement" which suffice, but I also wanted to show the OP that the compiler can NOT know that, it's a runtime thing.
undefined * 1is a valid javascript statement, why would the compiler have any issues with that?NaN.