prefer-as-const
NOTE: this rule is part of the
recommended rule set.Enable full set in
deno.json:{ "lint": { "rules": { "tags": ["recommended"] } } }Enable full set using the Deno CLI:
deno lint --rules-tags=recommended
This rule can be explictly included to or excluded from the rules present in the current tag by adding it to the
include or exclude array in deno.json:{ "lint": { "rules": { "include": ["prefer-as-const"], "exclude": ["prefer-as-const"] } } }Recommends using const assertion (as const) over explicitly specifying literal types or using type assertion.
When declaring a new variable of a primitive literal type, there are three ways:
- adding an explicit type annotation
- using normal type assertion (like
as "foo", or<"foo">) - using const assertion (
as const)
This lint rule suggests using const assertion because it will generally lead to a safer code. For more details about const assertion, see the official handbook.
Invalid:
let a: 2 = 2; // type annotation let b = 2 as 2; // type assertion let c = <2> 2; // type assertion let d = { foo: 1 as 1 }; // type assertion Valid:
let a = 2 as const; let b = 2 as const; let c = 2 as const; let d = { foo: 1 as const }; let x = 2; let y: string = "hello"; let z: number = someVariable;