我最近遇到了一个关于三元检查number | undefinedvar 的问题undefined,但由于我在编写代码时缺乏注意力,当数字为 0 时,它错误地指责它是未定义的值。
然后,我发现了关于strict-boolean-expressions ESLint 规则。
看起来非常有用和安全,但是,给出这个例子:
const text: string | undefined = stringOrUndefined1 || stringOrUndefined2 || undefined; // the strings can be empty
if (!text) // I was doing it this way to check if the value was falsy. With the new rule, it complains.
return;
if (text === undefined || text === '') // This works, but is 4x the length of the one above. I don't want to write …Run Code Online (Sandbox Code Playgroud) 我有一个带有联合返回类型的(比较)函数。它可以返回-1,1或0. 但是,当至少一个要比较的项目未定义时,我需要一种特殊情况(“结果”)。编译器允许我添加null作为潜在的返回值,但不允许NaN(这在某些情况下是有意义的,例如比较数字或日期)。
这编译
function myFunc(item1: MyType, item2: MyType): -1 | 0 | 1 | null {
...
}
Run Code Online (Sandbox Code Playgroud)
但对于这个,编译器说“找不到名称 NaN”:
function myFunc(item1: MyType, item2: MyType): -1 | 0 | 1 | NaN {
...
}
Run Code Online (Sandbox Code Playgroud)
为什么NaN不允许?有办法使用吗NaN?