no-unnecessary-type-assertion
Disallow type assertions that do not change the type of an expression.
此规则报告的一些问题可通过 --fix
ESLint 命令行选项自动修复。
该规则需要 类型信息 才能运行,但这会带来性能方面的权衡。
使用 as
类型断言,TypeScript 可以得知表达式的类型与预期不同。将 as
断言留在代码库中会增加视觉混乱并损害代码的可读性,因此如果它们不会改变表达式的类型,通常最佳做法是删除它们。此规则报告类型断言何时不更改表达式的类型。
¥TypeScript can be told an expression is a different type than expected using as
type assertions.
Leaving as
assertions in the codebase increases visual clutter and harms code readability, so it's generally best practice to remove them if they don't change the type of an expression.
This rule reports when a type assertion does not change the type of an expression.
- Flat Config
- Legacy Config
export default tseslint.config({
rules: {
"@typescript-eslint/no-unnecessary-type-assertion": "error"
}
});
module.exports = {
"rules": {
"@typescript-eslint/no-unnecessary-type-assertion": "error"
}
};
在线运行试试这个规则 ↗
示例
¥Examples
- ❌ Incorrect
- ✅ Correct
const foo = 3;
const bar = foo!;
Open in Playgroundconst foo = <number>(3 + 5);
Open in Playgroundtype Foo = number;
const foo = <Foo>(3 + 5);
Open in Playgroundtype Foo = number;
const foo = (3 + 5) as Foo;
Open in Playgroundconst foo = 'foo' as const;
Open in Playgroundfunction foo(x: number): number {
return x!; // unnecessary non-null
}
Open in Playgroundconst foo = <number>3;
Open in Playgroundconst foo = 3 as number;
Open in Playgroundlet foo = 'foo' as const;
Open in Playgroundfunction foo(x: number | undefined): number {
return x!;
}
Open in Playground选项
该规则接受以下选项:
type Options = [
{
/** A list of type names to ignore. */
typesToIgnore?: string[];
},
];
const defaultOptions: Options = [{}];
¥Options
typesToIgnore
A list of type names to ignore. Default: []
.
使用 @typescript-eslint/no-unnecessary-type-assertion: ["error", { typesToIgnore: ['Foo'] }]
,以下是正确的代码:
¥With @typescript-eslint/no-unnecessary-type-assertion: ["error", { typesToIgnore: ['Foo'] }]
, the following is correct code:
type Foo = 3;
const foo: Foo = 3;
Open in Playground何时不使用它
¥When Not To Use It
如果你不关心代码中是否有空操作类型断言,那么你可以关闭此规则。
¥If you don't care about having no-op type assertions in your code, then you can turn off 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.
'## 资源'