69 lines
1.5 KiB
Plaintext
69 lines
1.5 KiB
Plaintext
== Why is this an issue?
|
|
|
|
TypeScript provides two ways to tell the compiler that a literal value should be typed as a literal type like `42` rather than the primitive one `number`:
|
|
|
|
* `as const` tells TypeScript to infer the literal type automatically
|
|
* `as T` where `T` denotes a literal type to instruct TypeScript to infer the literal type explicitly
|
|
|
|
In practice, `as const` is preferred because the type checker doesn't need re-typing the literal value.
|
|
|
|
Therefore, the rule flags occurrences of explicit literal types that can be replaced with an `as const` assertion.
|
|
|
|
== How to fix it
|
|
|
|
Replace the explicit literal type assertion with `as const`.
|
|
|
|
=== Code examples
|
|
|
|
==== Noncompliant code example
|
|
|
|
[source,typescript,diff-id=1,diff-type=noncompliant]
|
|
----
|
|
class Foo {
|
|
public static foo: 42 = 42; // Noncompliant
|
|
|
|
// ...
|
|
}
|
|
----
|
|
|
|
==== Compliant solution
|
|
|
|
[source,typescript,diff-id=1,diff-type=compliant]
|
|
----
|
|
class Foo {
|
|
public static foo = 42 as const;
|
|
|
|
// ...
|
|
}
|
|
----
|
|
|
|
==== Noncompliant code example
|
|
|
|
[source,typescript,diff-id=2,diff-type=noncompliant]
|
|
----
|
|
let foo = { bar: 'baz' as 'baz' };
|
|
----
|
|
|
|
==== Compliant solution
|
|
|
|
[source,typescript,diff-id=2,diff-type=compliant]
|
|
----
|
|
let foo = { bar: 'baz' as const };
|
|
----
|
|
|
|
//=== How does this work?
|
|
|
|
//=== Pitfalls
|
|
|
|
//=== Going the extra mile
|
|
|
|
== Resources
|
|
|
|
=== Documentation
|
|
|
|
* TypeScript Documentation - https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#literal-types[Literal types]
|
|
|
|
//=== Articles & blog posts
|
|
//=== Conference presentations
|
|
//=== Standards
|