useAsConstAssertion
此内容尚不支持你的语言。
Diagnostic Category: lint/style/useAsConstAssertion
Since: v1.3.0
Sources:
- Same as:
@typescript-eslint/prefer-as-const
Enforce the use of as const
over literal type and type annotation.
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
: telling TypeScript to infer the literal type automaticallyas <literal>
: explicitly telling the literal type to TypeScript- type annotation: explicitly telling the literal type to TypeScript when declare variables
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
Section titled ExamplesInvalid
Section titled Invalidcode-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 │
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 │