eslint:if 条件的非隐式强制转换
eslint: no-implicit-coercion for if conditionals
我在 TypeScript 中使用带有 @typescript-eslint/eslint-plugin
的 eslint。
是否可以警告以下代码使用 any
type in if
条件?
我尝试了 no-implicit-coercion
规则,但没有用。
const foo = (a: any) => {
if (a) { // this should be warned
return 42;
} else {
return false;
}
}
您正在寻找 @typescript-eslint/strict-boolean-expressions
。
默认情况下,它禁止在条件语句中使用 any
,但也禁止可以为 null 的布尔值、可以为 null 的字符串和可以为 null 的数字。只禁止 any
你可以使用这个配置:
"rules": {
"@typescript-eslint/strict-boolean-expressions": [2, {
"allowNullableBoolean": true,
"allowNullableString": true,
"allowNullableNumber": true
}]
}
就个人而言,我不推荐这样做,我会保留默认设置的规则,因为它可以防止这样的错误(尽管是人为的例子):
declare const maybeNumber: number | null
if (maybeNumber) {
// number could actually be null, 0, or NaN!
console.log('maybeNumber is not null!') // oops
let thisIsNaN = 123 / maybeNumber
}
此外,您还可以使用 @typescript-eslint/no-explicit-any
来完全避免代码库中的 any
;请改用 unknown
。
我在 TypeScript 中使用带有 @typescript-eslint/eslint-plugin
的 eslint。
是否可以警告以下代码使用 any
type in if
条件?
我尝试了 no-implicit-coercion
规则,但没有用。
const foo = (a: any) => {
if (a) { // this should be warned
return 42;
} else {
return false;
}
}
您正在寻找 @typescript-eslint/strict-boolean-expressions
。
默认情况下,它禁止在条件语句中使用 any
,但也禁止可以为 null 的布尔值、可以为 null 的字符串和可以为 null 的数字。只禁止 any
你可以使用这个配置:
"rules": {
"@typescript-eslint/strict-boolean-expressions": [2, {
"allowNullableBoolean": true,
"allowNullableString": true,
"allowNullableNumber": true
}]
}
就个人而言,我不推荐这样做,我会保留默认设置的规则,因为它可以防止这样的错误(尽管是人为的例子):
declare const maybeNumber: number | null
if (maybeNumber) {
// number could actually be null, 0, or NaN!
console.log('maybeNumber is not null!') // oops
let thisIsNaN = 123 / maybeNumber
}
此外,您还可以使用 @typescript-eslint/no-explicit-any
来完全避免代码库中的 any
;请改用 unknown
。