Skip to content

useAsConstAssertion

诊断类别:lint/style/useAsConstAssertion

¥Diagnostic Category: lint/style/useAsConstAssertion

自从:v1.3.0

¥Since: v1.3.0

来源:

¥Sources:

强制使用 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:

  1. as const:告诉 TypeScript 自动推断文字类型

    ¥as const: telling TypeScript to infer the literal type automatically

  2. as <literal>:明确告知 TypeScript 文字类型

    ¥as <literal>: explicitly telling the literal type to TypeScript

  3. 类型注释:在声明变量时明确告知 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