Skip to main content

prefer-as-const

Enforce the use of as const over literal type.

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 与字面量类型: 明确地告诉 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.

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

示例

let bar: 2 = 2;
let foo = <'bar'>'bar';
let foo = { bar: 'baz' as 'baz' };
Open in Playground

何时不使用它

如果你不关心代码中使用哪种样式的字面量断言,那么你将不需要此规则。

英:If you don't care about which style of literals assertions is used in your code, then you will not need this rule.

但是,请记住,不一致的风格可能会损害项目的可读性。 我们建议为此规则选择一个最适合你的项目的选项。

英:However, keep in mind that inconsistent style can harm readability in a project. We recommend picking a single option for this rule that works best for your project.

选项

该规则不可配置。

资源