整数(文字)联合类型,以 NaN 作为有效 return 值

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

我有一个联合 return 类型的(比较)函数。它可以 return -110。但是,我需要一个特殊情况 ("result"),因为至少有一个被比较的项目未定义。编译器允许我添加 null 作为潜在的 return 值,但不能添加 NaN(这在某些情况下是有意义的,例如比较数字或日期)。

这样编译

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

但是对于这个,编译器说的是 "Cannot find name NaN":

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

为什么 NaN 不允许?有没有办法使用 NaN?

1 不同,NaN 不能用作 literal type(即仅包含该文字值的类型)。

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

我们也可以使用 number 作为 return 类型,但这将允许更多 return 值,例如 -2。如果您想限制选项,null 对我来说不错。

NaN 本身不是类型,而是 Number 类型的 const 值。因此无法将任何内容定义为 NaN 类型。

这是有道理的,因为数字的文字类型都是单值,例如-1,或文字值的并集 1 | 0 | -1NaN 不是单个值,因为没有 NaN 与任何其他值进行比较,它实际上是一组无限值。

我建议使用 NaN 来指示函数的特定结果是个坏主意,因为测试获得该结果的唯一方法是调用另一个函数。最好将 nullundefined 添加到 return 类型(或者,如果您不喜欢那样,可以使用文字字符串)。

请记住:

let foo = NaN;
switch(foo) {
    case 1: console.log('got 1'); break
    case NaN: console.log('got NaN'); break;
    default: console.log('other');
}

会输出'other'.

所以你可以这样做:

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

然后您可以将结果与 'not comparable'.

进行比较