Sub topic 13
Arrays, Tuples, and Readonly Arrays
Assume you know basic TypeScript types, interfaces, functions, arrays, and compiler errors. This chapter focuses on how assignability works for collection types.
Array assignability
An array type describes the element type and allows any number of elements:
interface Animal {
name: string;
}
interface Dog extends Animal {
bark(): void;
}
const dogs: Dog[] = [];
const animals: Animal[] = dogs;
animals.push({ name: "Milo" });
console.log(dogs[0].bark()); // Runtime error: the value is not a DogTypeScript treats Dog[] as assignable to Animal[]. This is called covariance: if Dog is assignable to Animal, then Dog[] is assignable to Animal[].
The rule is convenient because reading a dog as an animal is safe. However, a mutable Animal[] can accept any animal. That write can place a non-dog value into the original Dog[]. This is an intentional unsoundness in TypeScript.
A readonly array prevents that write:
const dogs: Dog[] = [];
const animals: readonly Animal[] = dogs;
// animals.push({ name: "Milo" }); // Error: readonly arrays have no push methodA mutable array can be assigned to a readonly array, but a readonly array cannot be assigned to a mutable array.
| Source type | Target type | Result |
|---|---|---|
| `Dog[]` | `readonly Animal[]` | Allowed |
| `readonly Dog[]` | `Animal[]` | Rejected |
| `Dog[]` | `Animal[]` | Allowed, but potentially unsound |
Tuples and their positions
A tuple is an array type with a known length and a type for each position:
type Entry = [string, number];
const entry: Entry = ["temperature", 21];
const key = entry[0]; // string
const value = entry[1]; // number
// const invalid: Entry = [21, "temperature"]; // ErrorTuple assignability checks position, length, and mutability. A readonly tuple can be created with as const:
const point = [10, 20] as const; // readonly [10, 20]
function distanceFromOrigin(value: readonly [number, number]): number {
return Math.sqrt(value[0] ** 2 + value[1] ** 2);
}
console.log(distanceFromOrigin(point));The function accepts both [number, number] and readonly [10, 20] because it promises only to read the tuple.
Common errors
Do not confuse an array with a tuple. number[] may contain any number of numbers, while [number, number] requires exactly two positions. Also remember that readonly applies to the collection itself. It does not automatically make objects inside the collection deeply readonly.
Exercise
Why can Dog[] be passed to a parameter of type readonly Animal[], but readonly Dog[] cannot be passed to Animal[]?
Show answer
Reading dogs as animals is safe, so mutable arrays can flow into readonly views. A readonly array cannot be passed to a mutable parameter because that parameter could call push or replace an element.