我在TypeScript中与TypeScript一起使用eslint。
是否可以警告在any
条件中使用if
类型的下列代码?我尝试过no-implicit-coercion
规则,但它没有起作用。
const foo = (a: any) => {
if (a) { // this should be warned
return 42;
} else {
return false;
}
}
发布于 2021-08-10 02:24:02
你在找@typescript-eslint/strict-boolean-expressions
。
默认情况下,它禁止条件数中的any
,但也禁止可空布尔值、可空字符串和可空数字。要仅禁止any
,可以使用以下配置:
"rules": {
"@typescript-eslint/strict-boolean-expressions": [2, {
"allowNullableBoolean": true,
"allowNullableString": true,
"allowNullableNumber": true
}]
}
但就我个人而言,我不建议这样做,我会保留默认设置的规则,因为它可以防止这样的bug(尽管只是一个人为的例子):
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
代替。
https://stackoverflow.com/questions/68720053
复制相似问题