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 const
: telling TypeScript to infer the literal type automatically -
as
带有文字类型:明确地告诉 TypeScript 字面量类型¥
as
with 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
.
- Flat Config
- Legacy Config
export default tseslint.config({
rules: {
"@typescript-eslint/prefer-as-const": "error"
}
});
module.exports = {
"rules": {
"@typescript-eslint/prefer-as-const": "error"
}
};
在线运行试试这个规则 ↗
示例
¥Examples
- ❌ Incorrect
- ✅ Correct
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选项
该规则不可配置。
何时不使用它
¥When Not To Use It
如果你不关心代码中使用哪种样式的字面量 断言,那么你将不需要此规则。
¥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.
'## 资源'