no-unsafe-type-assertion
Disallow type assertions that narrow a type.
该规则需要 类型信息 才能运行,但这会带来性能方面的权衡。
类型断言是一种告诉 TypeScript 值的类型的方法。如果你使用类型断言来缩小类型,这可能很有用,但也不安全。
¥Type assertions are a way to tell TypeScript what the type of a value is. This can be useful but also unsafe if you use type assertions to narrow down a type.
此规则禁止使用类型断言来缩小类型,因为这会绕过 TypeScript 的类型检查。扩大类型的类型断言是安全的,因为 TypeScript 本质上对类型的了解较少。
¥This rule forbids using type assertions to narrow a type, as this bypasses TypeScript's type-checking. Type assertions that broaden a type are safe because TypeScript essentially knows less about a type.
与其使用类型断言来缩小类型范围,不如依赖类型保护,这有助于避免由不安全的类型断言导致的潜在运行时错误。
¥Instead of using type assertions to narrow a type, it's better to rely on type guards, which help avoid potential runtime errors caused by unsafe type assertions.
- Flat Config
- Legacy Config
export default tseslint.config({
rules: {
"@typescript-eslint/no-unsafe-type-assertion": "error"
}
});
module.exports = {
"rules": {
"@typescript-eslint/no-unsafe-type-assertion": "error"
}
};
在线运行试试这个规则 ↗
示例
¥Examples
- ❌ Incorrect
- ✅ Correct
function f() {
return Math.random() < 0.5 ? 42 : 'oops';
}
const z = f() as number;
const items = [1, '2', 3, '4'];
const number = items[0] as number;
Open in Playgroundfunction f() {
return Math.random() < 0.5 ? 42 : 'oops';
}
const z = f() as number | string | boolean;
const items = [1, '2', 3, '4'];
const number = items[0] as number | string | undefined;
Open in Playground选项
该规则不可配置。
何时不使用它
¥When Not To Use It
如果你的代码库有许多不安全的类型断言,则可能很难启用此规则。在项目不安全区域中增加类型安全性时,跳过 no-unsafe-*
规则可能会更容易。你可以考虑在这些特定情况下使用 ESLint 禁用注释,而不是完全禁用此规则。
¥If your codebase has many unsafe type assertions, then it may be difficult to enable this rule.
It may be easier to skip the no-unsafe-*
rules pending increasing type safety in unsafe areas of your project.
You might consider using ESLint disable comments for those specific situations instead of completely disabling this rule.
如果你的项目经常在测试文件中存根对象,则该规则可能会触发大量报告。考虑禁用此类文件的规则以减少频繁警告。
¥If your project frequently stubs objects in test files, the rule may trigger a lot of reports. Consider disabling the rule for such files to reduce frequent warnings.
进一步阅读
¥Further Reading
-
有关 TypeScript 的 类型断言 的更多信息
¥More on TypeScript's type assertions
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.
'## 资源'