non-nullable-type-assertion-style
强制非空断言优于显式类型断言.
在 ESLint 配置 中扩展"plugin:@typescript-eslint/stylistic-type-checked"
可启用此规则。
此规则报告的一些问题可通过 --fix
ESLint 命令行选项自动修复。
该规则需要 类型信息 才能运行,但这会带来性能方面的权衡。
有两种常用方法可以向 TypeScript 断言一个值是其类 型,而无需 null
或 undefined
:
¥There are two common ways to assert to TypeScript that a value is its type without null
or undefined
:
-
!
:非空断言¥
!
: Non-null assertion -
as
:具有巧合等效类型的传统类型断言¥
as
: Traditional type assertion with a coincidentally equivalent type
!
非空断言通常是首选,因为它需要的代码更少,并且随着类型变化更难失去同步。此规则报告何时可以用 !
替换 as
调用。
¥!
non-null assertions are generally preferred for requiring less code and being harder to fall out of sync as types change.
This rule reports when an as
assertion is doing the same job as a !
would, and suggests fixing the code to be an !
.
- 扁平配置
- 旧版配置
export default tseslint.config({
rules: {
"@typescript-eslint/non-nullable-type-assertion-style": "error"
}
});
module.exports = {
"rules": {
"@typescript-eslint/non-nullable-type-assertion-style": "error"
}
};
在线运行试试这个规则 ↗
示例
¥Examples
- ❌ 错误
- ✅ 正确
const maybe: string | undefined = Math.random() > 0.5 ? '' : undefined;
const definitely = maybe as string;
const alsoDefinitely = <string>maybe;
Open in Playgroundconst maybe: string | undefined = Math.random() > 0.5 ? '' : undefined;
const definitely = maybe!;
const alsoDefinitely = maybe!;
Open in Playground选项
该规则不可配置。
何时不使用它
¥When Not To Use It
如果你不介意使用不必要的冗长类型断言,则可以避免此规则。
¥If you don't mind having unnecessarily verbose type assertions, you can avoid this rule.
Type checked lint rules are more powerful than traditional lint rules, but also require configuring type checked linting.
See Troubleshooting > Linting with Type Information > Performance if you experience performance degradations after enabling type checked rules.