Advertisement
Advanced TypeScript, Readonly, const Assertions & Immutability

How does 'readonly' modify the variance/assignability rules between array types compared to their mutable counterparts?

Short answer

A `readonly T[]` is CONTRAvariant-friendly in a way mutable arrays aren't: a `Dog[]` IS assignable to `readonly Animal[]` (since you can only READ from it, so treating dogs as animals is always safe), but a `Dog[]` is NOT safely assignable to a mutable `Animal[]` (since someone…

Save TypeScript mock interview
Advertisement
AModel answer
A `readonly T[]` is CONTRAvariant-friendly in a way mutable arrays aren't: a `Dog[]` IS assignable to `readonly Animal[]` (since you can only READ from it, so treating dogs as animals is always safe), but a `Dog[]` is NOT safely assignable to a mutable `Animal[]` (since someone could then push a Cat into what's actually a Dog array) — TypeScript actually allows the unsound mutable case too for practical reasons, but the readonly version is the genuinely SOUND direction.
interface Animal { name: string; }
interface Dog extends Animal { breed: string; }
const dogs: Dog[] = [{ name: 'Rex', breed: 'Lab' }];
const readonlyAnimals: readonly Animal[] = dogs; // sound and safe: read-only, so no invalid inserts possible
const mutableAnimals: Animal[] = dogs; // TypeScript allows this too, but it's technically unsound
Real-world example
Understanding a subtle but real class of type-safety loophole in TypeScript's array covariance rules, and why 'readonly' closes part of it.
Likely follow-ups
  • Why does TypeScript still allow the unsound mutable-array assignment despite readonly being the technically correct direction?
Related topics