ProgrammingFrontend Developer

How does the typing of constant objects with the `as const` property work? What are the advantages and what problems can arise from incorrect typing of such objects?

Pass interviews with Hintsage AI assistant

Answer

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:

  • Strict typing (for example, switch/case over strings, constant lists)
  • Ideal for enums, actionTypes in Redux, role lists, etc.
  • Prevents accidental changes to values

Disadvantages/Features:

  • Properties become readonly, attempts to change them will result in an error.
  • Careless usage can lead to type incompatibility (for example, if a string is needed, but a literal was passed).

Trick Question

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

Examples of Real Errors Due to Ignorance of Topic Nuances


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.