Skip to content
← Back to rules

typescript/prefer-as-const 正确性

This rule is turned on by default.
🛠️ An auto-fix is available for this rule for some violations.

它做了什么

强制使用 as const 而非字面量类型。

为什么这是不好的?

有两种常见方式告诉 TypeScript 将一个字面量值解释为其字面量类型(例如 2),而不是通用原始类型(例如 number):

  • as const:让 TypeScript 自动推断字面量类型
  • 使用字面量类型的 as:显式地告诉 TypeScript 该字面量类型

通常推荐使用 as const,因为它不需要重新输入字面量值。此规则会在可以将带有显式字面量类型的 as 替换为 as const 时进行报告。

示例

此规则的 错误 代码示例:

ts
let bar: 2 = 2;
let foo = { bar: "baz" as "baz" };

此规则的 正确 代码示例:

ts
let foo = "bar";
let foo = "bar" as const;
let foo: "bar" = "bar" as const;
let bar = "bar" as string;
let foo = { bar: "baz" };

如何使用

要通过配置文件或 CLI 启用 此规则,可以使用:

json
{
  "rules": {
    "typescript/prefer-as-const": "error"
  }
}
bash
oxlint --deny typescript/prefer-as-const

参考资料