@typescript-eslint/strict-boolean-expressions:联合类型应与allowOptions一起考虑

问题描述 投票:0回答:1

举个例子。

declare const str: string
if (str) { } good

declare const num: number
if(num) {} // good

declare const u: string | number
if(u) {} // Unexpected value in conditional. A boolean expression is required.ESLint@typescript-eslint/strict-boolean-expressions

我认为联合类型

u
不应该被报告。

typescript-eslint
1个回答
0
投票

你错了。规则

strict-boolean-expressions
描述为:

Forbids usage of non-boolean types in expressions where a boolean is expected. boolean and never types are always allowed. Additional types which are considered safe in a boolean context can be configured via options.

请记住,可以通过选项配置其他类型。那么让我们看看默认选项是什么样子的

const defaultOptions: Options = [
  {
    allowString: true,
    allowNumber: true,
    allowNullableObject: true,
    allowNullableBoolean: false,
    allowNullableString: false,
    allowNullableNumber: false,
    allowNullableEnum: false,
    allowAny: false,
    allowRuleToRunWithoutStrictNullChecksIKnowWhatIAmDoing: false,
  },
];

在我看来,这完美地解释了为什么前两个示例有效而最后一个示例失败

© www.soinside.com 2019 - 2024. All rights reserved.