useAsConstAssertion
¥Summary
-
规则生效日期:
v1.3.0¥Rule available since:
v1.3.0 -
诊断类别:
lint/style/useAsConstAssertion¥Diagnostic Category:
lint/style/useAsConstAssertion -
此规则包含 safe 修复程序。
¥This rule has a safe fix.
-
此规则的默认严重级别为 information。
¥The default severity of this rule is information.
-
来源:
¥Sources:
¥How to configure
{ "linter": { "rules": { "style": { "useAsConstAssertion": "error" } } }}¥Description
强制使用 as const 而不是文字类型和类型注释。
¥Enforce the use of as const over literal type and type annotation.
在 TypeScript 中,有三种常用方法可以指定值属于特定类型(例如 2)而不是一般类型(例如 number):
¥In TypeScript, there are three common ways to specify that a value is of a specific type such as 2 and not a general type such as number:
-
as const:告诉 TypeScript 自动推断文字类型¥
as const: telling TypeScript to infer the literal type automatically -
as <literal>:明确告知 TypeScript 文字类型¥
as <literal>: explicitly telling the literal type to TypeScript -
类型注释:在声明变量时明确告知 TypeScript 文字类型
¥type annotation: explicitly telling the literal type to TypeScript when declare variables
该规则建议在使用带有文字类型或类型注释的 as 时使用 as const,因为 as const 更简单并且不需要重新输入值。
¥The rule suggests to use as const when you’re using as with a literal type or type annotation, since as const is simpler and doesn’t require retyping the value.
¥Examples
¥Invalid
let bar: 2 = 2;code-block.ts:1:10 lint/style/useAsConstAssertion FIXABLE ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
ℹ Use as const instead of type annotation.
> 1 │ let bar: 2 = 2;
│ ^
2 │
ℹ as const doesn’t require any update when the value is changed.
ℹ Safe fix: Replace with as const.
1 │ - let·bar:·2·=·2;
1 │ + let·bar·=·2·as·const;
2 2 │
let foo = { bar: 'baz' as 'baz' };code-block.ts:1:27 lint/style/useAsConstAssertion FIXABLE ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
ℹ Use as const instead of as with a literal type.
> 1 │ let foo = { bar: ‘baz’ as ‘baz’ };
│ ^^^^^
2 │
ℹ as const doesn’t require any update when the asserted value is changed.
ℹ Safe fix: Replace with as const.
1 │ - let·foo·=·{·bar:·‘baz’·as·‘baz’·};
1 │ + let·foo·=·{·bar:·‘baz’·as·const·};
2 2 │
¥Valid
let foo = 'bar';let foo = 'bar' as const;let foo: 'bar' = 'bar' as const;let bar = 'bar' as string;let foo = { bar: 'baz' };¥Related links
Biome v2.1 中文网 - 粤ICP备13048890号