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

前端 未结 2 653
Happy的楠姐
Happy的楠姐 2020-12-12 00:59

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 wh

相关标签:
2条回答
  • 2020-12-12 01:22

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

    0 讨论(0)
  • 2020-12-12 01:32

    Unlike 1, NaN can not be used as a literal type (i.e. a type that only contain that literal value).

    const n1 = 1, n2 = NaN;
    typeof n1; // 1
    typeof n2; // number
    

    We could also use number as the return type, but this would allow more return values like -2. If you wanted to limit the options, null looks good to me.

    0 讨论(0)
提交回复
热议问题