Predict the output · TypeScript

readonly and as const at Runtime

Medium Predict the output Seen at Microsoft, Vercel

The casts silence the compiler. What does this print?

What does this print?

const config = { retries: 3 } as const;
(config as { retries: number }).retries = 5;

const list: readonly number[] = [1, 2];
(list as number[]).push(3);

console.log(config.retries, list.length);
  1. 3 2
  2. 5 3
  3. TypeError
  4. 3 3

Check your answer

Loading the editor… (JavaScript is required to run code in your browser.)

Solution

Show the answer

The output is:

5 3

readonly, ReadonlyArray and as const only exist in the type system and are erased when compiling. Once the types are bypassed (casts, any, or untyped JavaScript callers), the objects are fully mutable. For real runtime immutability use Object.freeze (shallow) or immutable data structures.