as const in TypeScript turns the values and properties of an object/array into readonly and literal types. This provides strict typing: values do not "expand" to their base type but maintain their specific value.
Example:
const a = { status: 'success' }; // Type: { status: string } const b = { status: 'success' } as const; // Type: { readonly status: "success" }
Advantages:
Disadvantages/Features:
Question: If you use as const for an array of strings, what will its type be, and can it be passed as a regular string[]?
Answer: The type will be readonly ["a", "b", "c"], meaning a tuple of literal types with a readonly restriction. Such an array is incompatible with the type string[]; it cannot be directly passed where a mutable array of strings is expected.
const arr = ['a', 'b', 'c'] as const; // readonly ["a", "b", "c"] function acceptsStrings(x: string[]) {} acceptsStrings(arr); // Error! Type incompatible
Story
Project: Kept a list of actionTypes as a constant array with as const, then tried to pass it to a function expecting string[]. Encountered a type error and had to explicitly convert it using
.slice()or[...arr].
Story
Project: In a Redux micro-framework, the type of action.type was defined as a literal using as const. When implementing switch-case, forgot about strict typing, did not handle all possible literals, which caused the exhaustive check to fail — the error did not manifest until a new action was added.
Story
Project: When auto-generating API endpoints, described their keys through an as const array. Attempting to use these keys as an index for a regular Record<string, ...> failed due to type mismatch — had to add a conversion or explicitly use the types of keys from the array.