Skip to main content

non-nullable-type-assertion-style

Enforce non-null assertions over explicit type casts.

🔧

此规则报告的一些问题可通过 --fix ESLint 命令行选项自动修复

💭

该规则需要 类型信息 才能运行。


有两种常见方法可以向 TypeScript 断言某个值是其类型(不带 nullundefined):

英:There are two common ways to assert to TypeScript that a value is its type without null or undefined:

  • !: 非空断言
  • as: 具有巧合等效类型的传统类型断言

! 非空断言通常是首选,因为它需要更少的代码,并且随着类型的变化更难失去同步。 此规则报告 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 cast is doing the same job as a ! would, and suggests fixing the code to be an !.

.eslintrc.cjs
module.exports = {
"rules": {
"@typescript-eslint/non-nullable-type-assertion-style": "error"
}
};
在线运行试试这个规则 ↗

示例

const maybe = Math.random() > 0.5 ? '' : undefined;

const definitely = maybe as string;
const alsoDefinitely = <string>maybe;
Open in Playground

何时不使用它

如果你不介意使用不必要的冗长类型断言,则可以避免此规则。

英:If you don't mind having unnecessarily verbose type assertions, you can avoid this rule.

选项

该规则不可配置。

资源