跳至主要內容

no-unnecessary-type-assertion

禁止不改變表達式類型的類型斷言。

🔧

此規則報告的一些問題可以通過 --fix ESLint 命令列選項.

自動修復。

💭 此規則需要 類型信息

才能運行。

可以使用 as 類型斷言告訴 TypeScript 表達式的類型與預期不同。在代碼庫中留下 as 斷言會增加視覺混亂並損害代碼可讀性,因此如果它們沒有改變表達式的類型,通常最好將它們刪除。此規則報告類型斷言何時不改變表達式的類型。
module.exports = {
"rules": {
"@typescript-eslint/no-unnecessary-type-assertion": "error"
}
};

.eslintrc.cjs

在 Playground 中嘗試此規則 ↗

const foo = 3;
const bar = foo!;
✅ 正確
const foo = <number>(3 + 5);
✅ 正確
type Foo = number;
const foo = <Foo>(3 + 5);
✅ 正確
type Foo = number;
const foo = (3 + 5) as Foo;
✅ 正確
const foo = 'foo' as const;
✅ 正確
function foo(x: number): number {
return x!; // unnecessary non-null
}
✅ 正確

在 Playground 中打開

選項

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

const defaultOptions: Options = [{}];

此規則接受以下選項

typesToIgnore

type Foo = 3;
const foo: Foo = 3;
✅ 正確

使用 @typescript-eslint/no-unnecessary-type-assertion: ["error", { typesToIgnore: ['Foo'] }],以下是正確的代碼

何時不使用


如果您不介意在代碼中使用無操作類型斷言,則可以關閉此規則。

類型檢查的 Lint 規則比傳統的 Lint 規則更強大,但也需要配置類型檢查的 Lint。如果您在啟用類型檢查規則後遇到性能下降,請參閱性能故障排除