NaN
itself is not a type, instead it is a const
value of type Number
. So there is no way to define anything as being of the type NaN.
That makes sense, because the literal types for numbers are all single values e.g. -1, or a union of the literal values 1 | 0 | -1
but NaN
isn't a single value as no NaN ever compares equal to any other it is effectively an infinite set of values.
I would suggest that using NaN
to indicate a particular result from your function is a bad idea as the only way you can test for getting that result is to call another function. Better to add null
or undefined
to the return type (or if you don't like that how about a literal string).
Keep in mind that:
let foo = NaN;
switch(foo) {
case 1: console.log('got 1'); break
case NaN: console.log('got NaN'); break;
default: console.log('other');
}
will output 'other'.
So you could just do this:
function myFunc(item1: MyType, item2: MyType): -1 | 0 | 1 | 'not comparable' {
...
}
and then you can just compare the result against 'not comparable'.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…