prefer-as-const
强制使用
as const优于字面量类型.
在 ESLint 配置 中扩展"plugin:@typescript-eslint/recommended" 可启用此规则。
此规则报告的一些问题可通过 --fix ESLint 命令行选项自动修复。
此规则报告的一些问题可以通过编辑器 建议 手动修复。
有两种常用方法可以告诉 TypeScript,字面量值应该解释为其字面量类型(例如 2),而不是一般的原始类型(例如 number);
¥There are two common ways to tell TypeScript that a literal value should be interpreted as its literal type (e.g. 2) rather than general primitive type (e.g. number);
-
as const:告诉 TypeScript 自动推断字面量类型¥
as const: telling TypeScript to infer the literal type automatically -
as带有字面量类型:明确地告诉 TypeScript 字面量类型¥
aswith the literal type: explicitly telling the literal type to TypeScript
as const 通常是首选,因为它不需要重新输入字面量值。此规则报告何时可以使用 as const 替换具有显式字面量类型的 as。
¥as const is generally preferred, as it doesn't require re-typing the literal value.
This rule reports when an as with an explicit literal type can be replaced with an as const.
- 扁平配置
- 旧版配置
export default tseslint.config({
rules: {
"@typescript-eslint/prefer-as-const": "error"
}
});
module.exports = {
"rules": {
"@typescript-eslint/prefer-as-const": "error"
}
};
在线运行试试这个规则 ↗
示例
¥Examples
- ❌ 错误
- ✅ 正确
let bar: 2 = 2;
let foo = <'bar'>'bar';
let foo = { bar: 'baz' as 'baz' };
Open in Playgroundlet 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' };
Open in Playground选项
该规则不可配置。