Sub topic 7
Arrays Are Covariant (Unsoundly); ReadonlyArray Is Safe
Assume you know TypeScript generics, structural typing, assignability, and the strict compiler option. This chapter focuses on how array mutability affects variance.
Array covariance
Covariance means that a generic type keeps the assignment direction of its type argument. Since Dog is assignable to Animal, TypeScript allows Dog[] to be assigned to Animal[].
class Animal {
name = "animal";
}
class Dog extends Animal {
bark() {
return "woof";
}
}
const dogs: Dog[] = [new Dog()];
const animals: Animal[] = dogs; // Allowed: Dog[] is treated as a subtype of Animal[]
animals.push(new Animal()); // Also allowed through the Animal[] reference
const secondDog = dogs[1]!;
try {
console.log(secondDog.bark()); // Runtime error: bark is not a function
} catch (error) {
console.log("The array contained an Animal that was not a Dog.");
}The assignment is convenient because code that only reads animals can usually read dogs. However, Animal[] also has a write operation: push accepts any Animal. The compiler therefore permits a non-Dog value to enter the original Dog[].
The type system has accepted an operation that can fail at runtime. This is called unsoundness. TypeScript allows some unsound behavior to remain practical and compatible with common JavaScript code.
ReadonlyArray is safely covariant
ReadonlyArray<T> describes an array-like value that can be read but not changed through that reference. It produces T values without consuming them through mutating methods.
const dogs: Dog[] = [new Dog()];
const animals: ReadonlyArray<Animal> = dogs; // Safe covariance
for (const animal of animals) {
console.log(animal.name);
}
// animals.push(new Animal()); // Error: ReadonlyArray has no push methodThe original dogs variable remains mutable, but the animals reference cannot use that mutability. This makes the assignment sound from the type system's point of view.
You can write the same type with the shorthand readonly T[]:
function printAnimals(animals: readonly Animal[]): void {
for (const animal of animals) {
console.log(animal.name);
}
}
printAnimals(dogs); // Dog[] can be passed to readonly Animal[]Use readonly in function parameters when a function only needs to inspect a collection. This accepts both mutable and immutable arrays and prevents the function from changing its caller's data.
The variance model
The array example follows this pattern:
Dog[] is treated covariantly even though mutation makes that relationship unsafe. ReadonlyArray<Dog> to ReadonlyArray<Animal> is safe because the wider view cannot insert an arbitrary Animal.
Exercise
Why is ReadonlyArray<Dog> safely assignable to ReadonlyArray<Animal>, while a mutable array can cause a runtime failure?
Show answer
A readonly array only produces values, so reading a Dog as an Animal is safe. A mutable Animal array can also consume values, allowing a non-Dog Animal to be inserted into the original Dog array.