Skip to main content

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.

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

示例

const foo = 3;
const bar = foo!;
Open in Playground
const foo = <3>3;
Open in Playground
type Foo = 3;
const foo = <Foo>3;
Open in Playground
type Foo = 3;
const foo = 3 as Foo;
Open in Playground
function foo(x: number): number {
return x!; // unnecessary non-null
}
Open in Playground

选项

typesToIgnore

对于 @typescript-eslint/no-unnecessary-type-assertion: ["error", { typesToIgnore: ['Foo'] }],以下是 correct 代码:

英: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

何时不使用它

如果你不关心代码中是否有空操作类型断言,那么你可以关闭此规则。

英:If you don't care about having no-op type assertions in your code, then you can turn off this rule.

选项

该规则接受以下选项

type Options = [
{
/** A list of type names to ignore. */
typesToIgnore?: string[];
},
];

const defaultOptions: Options = [{}];

资源