Sub topic 4
Arrays Become Readonly Tuples
Prerequisites
This chapter assumes that you know basic TypeScript arrays, object types, union types, and the difference between let and const. You should also know that a tuple is an array type with a fixed number of positions, where each position can have a different type.
An ordinary array describes a collection of values. A tuple describes the meaning of each position.
const names: string[] = ["Ada", "Linus"];
const record: [string, number] = ["Ada", 36];The names array can contain any number of strings. The record tuple must contain exactly two values: a string at index 0 and a number at index 1.
Applying `as const` to an Array
When TypeScript sees an array literal, it normally widens the elements to general types and infers a mutable array:
const pair = ["id", 1];
// (string | number)[]The exact values "id" and 1 are lost from the type. TypeScript assumes that the array might later contain another string or number.
Adding as const changes this inference:
const pair = ["id", 1] as const;
// readonly ["id", 1]This type has three important properties:
readonlymeans the array cannot be changed through this value.["id", 1]means the length is fixed at two elements.- Each position keeps its literal type. Index
0is"id", and index1is1.
const pair = ["id", 1] as const;
const first = pair[0]; // type: "id"
const second = pair[1]; // type: 1
// pair.push(2); // Error: push does not exist on a readonly tuple
// pair[0] = "name"; // Error: index 0 is read-onlyThe tuple still exists as a normal JavaScript array at runtime. as const changes the type that TypeScript checks; it does not create a special JavaScript data structure.
How Inference Changes
The following table compares common array declarations:
| Declaration | Inferred type | Can change through the variable? |
|---|---|---|
| `let values = ["a", "b"]` | `string[]` | Yes |
| `const values = ["a", "b"]` | `string[]` | Yes, through methods such as `push` |
| `const values = ["a", "b"] as const` | `readonly ["a", "b"]` | No |
The const keyword prevents reassignment of the variable. It does not make the array contents readonly.
const normal = ["a", "b"];
normal.push("c"); // OK
// normal = ["x"]; // Error: the variable cannot be reassigned
const fixed = ["a", "b"] as const;
// fixed.push("c"); // Error
// fixed[0] = "x"; // ErrorUse as const when the positions and values are part of the meaning of the data. For a general collection that will grow or change, use a normal array type instead.
Reading Tuple Positions
A readonly tuple is useful when each position has a known purpose. For example, a result might contain a status code followed by a message:
const result = [200, "OK"] as const;
const statusCode = result[0]; // 200
const message = result[1]; // "OK"The compiler can use these exact types in later checks:
function handleResult(value: readonly [200 | 404, string]): string {
const [status, message] = value;
if (status === 404) {
return `Missing: ${message}`;
}
return `Success: ${message}`;
}
const response = [200, "OK"] as const;
console.log(handleResult(response)); // Success: OKThe parameter is readonly because handleResult only reads the tuple. This allows the function to accept both mutable and readonly tuples when their element types match.
A Tuple Is More Precise Than an Array
Consider these two types:
type PairArray = (string | number)[];
type PairTuple = readonly [string, number];PairArray allows any length and permits either type at every position:
const a: PairArray = ["id", 1, "extra"];PairTuple requires exactly two positions and gives each position its own type:
const b: PairTuple = ["id", 1];
// const wrong: PairTuple = [1, "id"]; // Error: positions have the wrong types
// const short: PairTuple = ["id"]; // Error: the second position is missingAdding as const to a literal can let TypeScript infer this precision without writing the tuple type manually.
Passing Readonly Tuples to Functions
A readonly tuple cannot be passed to a function that promises it may mutate a regular array:
function addValue(values: number[]): void {
values.push(4);
}
const numbers = [1, 2, 3] as const;
// addValue(numbers); // Error: readonly tuple is not assignable to number[]This error protects the tuple. If addValue accepted numbers, it could append a value and break the fixed-length guarantee.
When a function only reads its input, declare a readonly array or tuple parameter:
function total(values: readonly number[]): number {
return values.reduce((sum, value) => sum + value, 0);
}
const numbers = [1, 2, 3] as const;
console.log(total(numbers)); // 6A readonly number[] parameter accepts mutable arrays and readonly arrays. It communicates that the function will not change the caller's data.
The Runtime Boundary
A const assertion is checked only by the TypeScript compiler. It does not freeze an array at runtime.
const values = [1, 2] as const;
const mutableValues = values as unknown as number[];
mutableValues.push(3);
console.log(values); // [1, 2, 3]The cast in this example deliberately bypasses the type system. The JavaScript array remains mutable. If runtime immutability matters, use a separate runtime strategy such as copying the array or calling Object.freeze.
Exercise
What is the inferred type of const point = [10, 20] as const, and why can point.push(30) not be used?
Show answer
Its type is readonly [10, 20]. The assertion preserves the two literal element types, fixes the tuple length, and marks the tuple as readonly, so mutation methods such as push are unavailable.