【发布时间】:2021-03-04 12:38:08
【问题描述】:
我最近遇到了一个关于三元检查 number | undefined var 是否为 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 the var name more than once
if (!!text == false) // "Unexpected nullable string value in conditional. Please handle the nullish/empty cases explicitly."
if (!!!text) // Same warn as above
有没有什么方法可以在没有冗长的第二个条件并且不禁用规则的情况下快速准确地检查值是否为假,即使只是针对特定行?
我知道可以仅为可空字符串禁用,但这个问题也适用于数字,出于安全原因我想保留这条规则。
【问题讨论】:
-
strict-boolean-expressions 规则的目的是警告隐式转换为布尔值;只有当您确实需要这些隐式转换时,“真实”或“虚假”才重要。
!!text需要将应用的第一个!隐式转换为布尔值;目前尚不清楚您在哪些情况下需要警告,哪些情况下不需要。 -
由于这里的答案是有效的,如果不注释代码来解释为什么要使用它们,它们确实不够好使用。我认为检查虚假值的最佳选择是简单且合乎逻辑的
text == falseJS 允许。但是,Typescript 上已经发布了一个不允许它的错误。
标签: typescript eslint typescript-eslint