TypeScript "as const" explained
TypeScript
14/11/2022
as const
in TypeScript is known as const assertion. By appending it to a literal value (e.g. object literals, string literals or array literals), we tell the TypeScript compiler to assume the most narrow type definition for that value.
This can be best shown with an example:
TYPESCRIPT
const fruits = ["apple", "banana"]// const fruits: string[]const vegetables = ["lettuce", "broccoli", "beans"] as const// const vegetables: readonly ["lettuce", "broccoli", "beans"]
In the first array, TypeScript assumes that fruits
is an array of strings. However, in the 2nd array with the use of a const assertion, TypeScript assumes vegetables
is an array with 3 elements of type lettuce
, broccoli
and beans
, in that exact order.
Most importantly, however, it will render them immutable.
TYPESCRIPT
vegetables[2] = "corn"// Cannot assign to '2' because it is a read-only property.vegetables.push("corn")// Property 'push' does not exist on type 'readonly ["lettuce", "broccoli", "beans"]'.
Yet, be aware that there exist a few exceptions to this rule of immutability.