Advertisement
Beginner TypeScript, Readonly, const Assertions & Immutability

What does the 'as const' assertion do when applied to an object literal?

Short answer

'as const' locks every property to its most specific literal type (rather than the general widened type like 'string' or 'number') AND makes every property (recursively) readonly, essentially treating the object literal as an immutable, precisely-typed constant.

Save TypeScript mock interview
Advertisement
AModel answer
'as const' locks every property to its most specific literal type (rather than the general widened type like 'string' or 'number') AND makes every property (recursively) readonly, essentially treating the object literal as an immutable, precisely-typed constant.
const config = { theme: 'dark', maxRetries: 3 } as const;
// theme: 'dark' (literal), not string
// maxRetries: 3 (literal), not number
// config.theme = 'light'; // Error: readonly
Real-world example
Defining a precise, immutable configuration object whose exact literal values should be preserved in the type system.
Likely follow-ups
  • Without 'as const', what wider types would 'theme' and 'maxRetries' have been inferred as instead?
Related topics