prefer-as-const
強制使用
as const
取代字面量類型。
✅
擴展 "plugin:@typescript-eslint/recommended"
在 ESLint 配置 中啟用此規則。
🔧
此規則報告的一些問題可以通過 --fix
ESLint 命令列選項.
自動修復
有兩種常見的方法可以告訴 TypeScript 將字面量值解釋為其字面量類型(例如 2
)而不是一般的基本類型(例如 number
);
as const
:告訴 TypeScript 自動推斷字面量類型as
與字面量類型:明確地告訴 TypeScript 字面量類型
通常首選 as const
,因為它不需要重新輸入字面量值。當可以使用 as const
替換帶有顯式字面量類型的 as
時,此規則會報告。
.eslintrc.cjs
module.exports = {
"rules": {
"@typescript-eslint/prefer-as-const": "error"
}
};
在 Playground 中嘗試此規則 ↗
範例
- ❌ 不正確
- ✅ 正確
let bar: 2 = 2;
let foo = <'bar'>'bar';
let foo = { bar: 'baz' as 'baz' };
在 Playground 中開啟let foo = 'bar';
let foo = 'bar' as const;
let foo: 'bar' = 'bar' as const;
let bar = 'bar' as string;
let foo = <string>'bar';
let foo = { bar: 'baz' };
在 Playground 中開啟選項
此規則不可配置。
何時不使用它
如果您不關心程式碼中使用哪種風格的字面量斷言,則不需要此規則。
但是,請記住,不一致的風格可能會損害專案的可讀性。我們建議為此規則選擇一個最適合您專案的選項。