整数(文字)联合类型,以 NaN 作为有效返回值 [英] Integer (literal) union type, with NaN as valid return value

查看:30
本文介绍了整数(文字)联合类型,以 NaN 作为有效返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有联合返回类型的(比较)函数.它可以返回-110.但是,我需要一个特殊情况(结果"),用于当至少一个要比较的项目未定义时.编译器允许我添加 null 作为潜在的返回值,但不允许添加 NaN(这在某些情况下是有意义的,例如比较数字或日期).

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

这个编译

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

但是对于这个,编译器说它找不到名称 NaN":

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

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

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

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

推荐答案

NaN 本身不是类型,而是 Number 类型的 const.所以没有办法将任何东西定义为 NaN 类型.

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.

这是有道理的,因为数字的文字类型都是单个值,例如-1,或文字值的并集 1 |0 |-1NaN 不是单个值,因为没有 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.

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

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

请记住:

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

将输出其他".

所以你可以这样做:

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

然后您可以将结果与不可比较"进行比较.

and then you can just compare the result against 'not comparable'.

这篇关于整数(文字)联合类型,以 NaN 作为有效返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆