Hen*_*uno 10 typescript eslint typescript-eslint
我最近遇到了一个关于三元检查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
Run Code Online (Sandbox Code Playgroud)
有没有什么方法可以快速而良好地检查该值是否为假,而无需冗长的第二个条件,并且无需禁用规则,即使只是针对特定行?
我知道可以仅禁用可为空的字符串,但这个问题也适用于数字,这是出于安全原因我想保留的规则。
che*_*som 16
您可以尝试使用空合并运算符 ( ??
),如下所示:
if (!(text ?? '')) {}
Run Code Online (Sandbox Code Playgroud)
text ?? ''
评估''
是否是undefined
,text
否则。
这相当于以下内容:
if (!(text !== null && text !== undefined ? text : '')) {}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
32311 次 |
最近记录: |