Sub topic 2
Arrays become readonly tuples
This chapter assumes basic TypeScript types, unions, arrays, typeof, and keyof. It also assumes you know that const prevents reassignment of a variable, but does not automatically make its contents immutable.
Arrays become readonly tuples
An array literal normally widens into a mutable array type:
const pair = ["id", 1];
// (string | number)[]
pair.push("name"); // allowedWith as const, TypeScript keeps each literal type and the position of each element. The result is a readonly tuple, which is an array with a fixed length and known type at every position.
const pair = ["id", 1] as const;
// readonly ["id", 1]
const first = pair[0]; // "id"
// pair.push(2); // Error: push does not exist
// pair[0] = "name"; // Error: index 0 is readonlyDeriving union types from values
A const tuple can be the single source of truth for both runtime data and a type:
const ROLES = ["admin", "editor", "viewer"] as const;
type Role = (typeof ROLES)[number];
// "admin" | "editor" | "viewer"
function isRole(value: string): value is Role {
return (ROLES as readonly string[]).includes(value);
}
console.log(isRole("editor")); // true
console.log(isRole("owner")); // falsetypeof ROLES gets the tuple type. Indexing that type with number gets the union of all element types.
Passing readonly values to functions
A readonly tuple cannot be passed to a function that might mutate an array:
function sum(nums: readonly number[]): number {
return nums.reduce((total, n) => total + n, 0);
}
const values = [1, 2, 3] as const;
console.log(sum(values)); // 6Use readonly in a parameter when the function only reads its input. This accepts both mutable arrays and readonly arrays.
Exercise
What is the type of const pair = ["x", 10] as const, and why can a function accepting readonly (string | number)[] read it?
Show answer
Its type is readonly ["x", 10]. It is a readonly tuple, which is compatible with a readonly array because the function promises not to mutate it.