Sub topic 7
Arrays are covariant (unsoundly); ReadonlyArray is safe
This chapter assumes you know generic interfaces, structural typing, and the strict compiler option. It also assumes you have read the earlier chapters on covariance, invariance, and why method declarations stay bivariant. Here you will see how those ideas combine in the most common generic type in TypeScript, the array.
What the compiler allows
Earlier chapters used a read-and-write Box<T> that is invariant. By that logic Dog[] should not be assignable to Animal[], because an array can be read and written. TypeScript accepts the assignment anyway.
class Animal {
name = "animal";
}
class Dog extends Animal {
bark() {
return "woof";
}
}
const dogs: Dog[] = [new Dog()];
const animals: Animal[] = dogs; // Allowed: arrays are treated covariantly
animals.push(new Animal()); // Compiles, but dogs now holds a non-Dog
for (const d of dogs) {
console.log(d.bark());
}This program compiles without errors under strict. At runtime it prints woof for the first element. On the second element it throws TypeError: d.bark is not a function.
The type of dogs promises that every element has a bark method. The alias animals points at the same object, and its type allows pushing any Animal. The compiler never relates the two views, so the promise is broken.
Why arrays end up covariant
Array<T> uses T in both input and output positions:
Tis an output inat(index): T | undefined, in iteration, and in indexed reads.Tis an input inpush(...items: T[]),unshift(...items: T[]), andincludes(searchElement: T).
A type with both usages would normally be invariant. The input positions are written as method declarations, though, and you saw in the previous chapter that method parameters are compared bivariantly, even under strictFunctionTypes. Bivariant parameters accept either direction, so they do not stop covariance. The output positions require Dog to be assignable to Animal, and that holds. The result is that Array<Dog> is assignable to Array<Animal>.
This was a deliberate trade-off. Treating arrays as invariant would have rejected a great deal of ordinary code, such as passing a Dog[] to a function that only reads Animal[]. The language chose convenience over soundness here.
The same choice shows up in function parameters. A function that merely accepts Animal[] can silently break a caller's Dog[]:
class Animal {
name = "animal";
}
class Dog extends Animal {
bark() {
return "woof";
}
}
function addGeneric(list: Animal[]): void {
list.push(new Animal()); // looks harmless inside this function
}
const kennel: Dog[] = [new Dog()];
addGeneric(kennel); // Compiles. kennel is no longer a valid Dog[].The function looks correct in isolation and the call site looks correct in isolation. The bug exists only in the combination.
ReadonlyArray removes the unsound half
The unsoundness comes entirely from writing through a wider type. ReadonlyArray<T>, also written readonly T[], has no mutating methods, so the problem cannot arise through that type.
class Animal {
name = "animal";
}
class Dog extends Animal {
bark() {
return "woof";
}
}
function printNames(list: ReadonlyArray<Animal>): void {
for (const a of list) {
console.log(a.name);
}
// list.push(new Animal()); // Error: Property 'push' does not exist on type 'readonly Animal[]'.
}
const dogs: Dog[] = [new Dog()];
const safe: ReadonlyArray<Animal> = dogs; // OK and sound: no writes possible
printNames(safe);
printNames(dogs); // a mutable array is accepted wherever a readonly one is expectedHere T appears only in output positions, so covariance is correct and safe. The one input position left is includes(searchElement: T) (and indexOf), and those are methods, so bivariance covers them. Reading through a wider type never lies about what you get back.
Assignability between the two array types is one-directional:
| From | To | Allowed | Reason |
|---|---|---|---|
| `Dog[]` | `Animal[]` | Yes, unsound | Covariant by the method-bivariance rule |
| `Dog[]` | `ReadonlyArray<Animal>` | Yes, sound | Covariant, and no writes exist |
| `Animal[]` | `Dog[]` | No | `Animal` lacks `bark()` |
| `ReadonlyArray<Dog>` | `Dog[]` | No | A read-only view must not become mutable |
The last row is an error: The type 'readonly Dog[]' is 'readonly' and cannot be assigned to the mutable type 'Dog[]'. It is the one case where TypeScript refuses to widen your permissions.
Writing an API that avoids the trap
A function should say what it does to its array parameter. A signature that only reads should take a readonly type. Callers can then pass Dog[] or Animal[], and the compiler stops the body from mutating it.
class Animal {
name = "animal";
}
class Dog extends Animal {
bark() {
return "woof";
}
}
function firstName(list: readonly Animal[]): string | undefined {
return list[0]?.name;
}
function addDog(list: Dog[]): void {
list.push(new Dog());
}
const dogs: Dog[] = [new Dog()];
const animals: Animal[] = [new Animal()];
console.log(firstName(dogs)); // OK
console.log(firstName(animals)); // OK
addDog(dogs); // OK
// addDog(animals); // Error: Animal[] is not assignable to Dog[]A function that writes should name the exact element type it needs. addDog rejects Animal[] because an Animal[] could contain values that violate the contract Dog[] makes, and the compiler checks that direction correctly.
When you do need a wider mutable array, copy instead of aliasing:
class Animal {
name = "animal";
}
class Dog extends Animal {
bark() {
return "woof";
}
}
const dogs: Dog[] = [new Dog()];
const animals: Animal[] = [...dogs]; // a new array, so no shared state
animals.push(new Animal()); // dogs is unaffected
console.log(dogs.length, animals.length); // 1 2What a sound array would look like
The compiler's rule depends on how a type is declared, not on what it conceptually represents. A type that writes through a function-typed property is checked contravariantly under strictFunctionTypes, so T becomes invariant. You can combine that with the in out modifier from earlier chapters to get a sound, array-like type:
class Animal {
name = "animal";
}
class Dog extends Animal {
bark() {
return "woof";
}
}
interface StrictList<in out T> {
readonly items: ReadonlyArray<T>;
add: (item: T) => void; // property syntax, so checked contravariantly
}
declare const dogList: StrictList<Dog>;
// const animalList: StrictList<Animal> = dogList; // Error: invariant in TAn out-only read-only list, which mirrors ReadonlyArray, is also expressible:
class Animal {
name = "animal";
}
class Dog extends Animal {
bark() {
return "woof";
}
}
interface ReadList<out T> {
readonly length: number;
at(index: number): T | undefined;
}
declare const dogView: ReadList<Dog>;
const animalView: ReadList<Animal> = dogView; // OK: T only appears in outputsYou cannot apply these modifiers to the built-in Array interface, because it is a library declaration you do not control. For your own collection types, though, choosing method or property syntax, plus an explicit annotation, decides whether the compiler guards the assignment.
Checklist
- Treat
Dog[]toAnimal[]as a hole that exists for convenience, not as a guarantee. - Declare read-only parameters as
readonly T[]orReadonlyArray<T>. - Make writing functions demand the exact element type.
- Copy an array with a spread when you need a wider mutable one.
- Remember that
readonlyrestricts one reference, not the underlying data.
Exercise
In the snippet below, which line produces a compile error, and what is the safest one-word change to the signature of count so the other calls keep working?
class Animal { name = "animal"; }
class Dog extends Animal { bark() { return "woof"; } }
function count(list: Animal[]): number {
return list.length;
}
const dogs: Dog[] = [new Dog()];
const readonlyDogs: readonly Dog[] = dogs;
count(dogs);
count(readonlyDogs);
Show answer
The line count(readonlyDogs); fails, because a readonly Dog[] cannot be assigned to the mutable Animal[] parameter. Changing the parameter to readonly Animal[] (adding the word readonly) accepts both dogs and readonlyDogs. It also states that count does not mutate its argument.
Exercise
Why does the compiler accept const animals: Animal[] = dogs; for a Dog[], even though Array<T> uses T in the parameter of push?
Show answer
push and the other mutating members are declared with method syntax. Method parameters are compared bivariantly even under strictFunctionTypes, so those input positions do not force invariance. The output positions require Dog to be assignable to Animal, which holds, so Array<Dog> is assignable to Array<Animal>. This is why pushing an Animal through the alias compiles and corrupts the original array.