Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

typescript - Integer (literal) union type, with NaN as valid return value

I have a (comparison) function with an union return type. It can return -1, 1 or 0. However, I need a special case ("result") for when at least one of the items being compared is not defined. The compiler allows me to add null as a potential return value, but not NaN (which, in some scenarios would make sense, e.g. comparing numbers or dates).

This compiles

function myFunc(item1: MyType, item2: MyType): -1 | 0 | 1 | null {
   ...
}

but for this one, the compiler says it "Cannot find name NaN":

function myFunc(item1: MyType, item2: MyType): -1 | 0 | 1 | NaN {
   ...
}

Why is NaN not allowed? Is there a way to use NaN?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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'.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...