@typescript-eslint strict-boolean-expressions 检查虚假值

Hen*_*uno 10 typescript eslint typescript-eslint

我最近遇到了一个关于三元检查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 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 ?? ''评估''是否是undefinedtext否则。

这相当于以下内容:

if (!(text !== null && text !== undefined ? text : '')) {}
Run Code Online (Sandbox Code Playgroud)

  • 这可能是针对这种特殊情况的最佳答案。这意味着您的代码清晰明确。使用 `??` 运算符使您的条件清楚地意味着“我正在以与空字符串情况完全相同的方式处理空值情况”。 (2认同)