Sub topic 4
Arrays become readonly tuples
This chapter assumes you know basic TypeScript types, the difference between let and const, and literal types such as "a" | "b". It also assumes you can use typeof and keyof in type positions. The previous chapters covered literal widening and how as const treats object literals. Here we look at what it does to array literals.
What an array literal normally becomes
When you write an array literal with no annotation, TypeScript infers a mutable array. Its element type is the widened union of the element types.
const nums = [1, 2, 3]; // number[]
const mixed = ["id", 1]; // (string | number)[]
const flags = [true, false]; // boolean[]
const empty = []; // any[] (evolves as you push)The inference is reasonable for most code. A literal like ["id", 1] could be a list that grows and holds any strings and numbers. TypeScript can't assume you meant "exactly a string, then a number."
The inferred type loses three things:
- Position.
mixed[0]isstring | number, notstring. - Length.
mixed.lengthisnumber, so you can't tell it has two elements. - Exact values. Nothing records that the first element was
"id".
Adding as const to the literal keeps all three.
What `as const` does to an array
Applying as const to an array literal produces a readonly tuple. A tuple is an array type with a fixed length and a known type at each position.
const pair = ["id", 1] as const;
// readonly ["id", 1]
const first = pair[0]; // "id"
const second = pair[1]; // 1
const len = pair.length; // 2Three changes happen at once.
- The array becomes a tuple. The type lists one entry per element, in order.
- Each element keeps its literal type.
"id"stays"id"and1stays1. Widening is switched off for everything inside the literal. - The tuple is
readonly. Operations that change it are removed from its type.
The diagram shows both paths from the same source literal.
Reading with a known shape
Because the type knows the length, reading past the end is a compile-time error. This is stricter than ordinary arrays, which let you index anywhere.
const pair = ["id", 1] as const;
// pair[2];
// error: Tuple type 'readonly ["id", 1]' of length '2' has no element at index '2'.
const [kind, value] = pair;
// kind: "id", value: 1
// const [a, b, c] = pair;
// error: Tuple type 'readonly ["id", 1]' of length '2' has no element at index '2'.Destructuring uses the positions, so each variable gets its own precise type. With a plain (string | number)[], both kind and value would be string | number.
Writing is blocked
The readonly modifier removes every method that mutates the array. The assignment forms are rejected too.
const pair = ["id", 1] as const;
// pair.push(2);
// error: Property 'push' does not exist on type 'readonly ["id", 1]'.
// pair.sort();
// error: Property 'sort' does not exist on type 'readonly ["id", 1]'.
// pair[0] = "name";
// error: Cannot assign to '0' because it is a read-only property.Methods that return a new value still work. These include map, filter, slice, concat, join, indexOf, and includes. Iteration with for...of and spreading also work.
const pair = ["id", 1] as const;
const labels = pair.map((item) => String(item)); // string[]
const copy = pair.slice(); // ("id" | 1)[]
for (const item of pair) {
console.log(item); // item: "id" | 1
}slice() is a simple way to get a mutable array of the same elements. The result is an ordinary array, so it has lost the tuple's length and positions.
Comparing the four ways to type a literal
Developers often confuse a const tuple with a tuple annotation. They are different types.
| Declaration | Resulting type | Length known | Element values known | Mutable | Column |
|---|---|---|---|---|---|
| `const a = ["id", 1]` | `(string \ | number)[]` | No | No | Yes |
| `const b: [string, number] = ["id", 1]` | `[string, number]` | Yes | No (only the types) | Yes | |
| `const c: readonly [string, number] = ["id", 1]` | `readonly [string, number]` | Yes | No (only the types) | No | |
| `const d = ["id", 1] as const` | `readonly ["id", 1]` | Yes | Yes | No |
An annotation such as [string, number] describes a shape you choose. as const records what the literal actually contains. Use an annotation when the contract is "any string, then any number". Use as const when the exact values matter, for example when you derive types from them.
Nested arrays and objects
The assertion applies to the whole literal, including everything nested inside it. Every nested array becomes a readonly tuple and every nested object gets readonly properties with literal types.
const grid = [
[1, 2],
[3, 4],
] as const;
// readonly [readonly [1, 2], readonly [3, 4]]
const users = [
{ id: 1, name: "Ada" },
{ id: 2, name: "Lin" },
] as const;
// readonly [
// { readonly id: 1; readonly name: "Ada" },
// { readonly id: 2; readonly name: "Lin" }
// ]
const secondName = users[1].name; // "Lin"The depth is the main difference from Object.freeze, which is shallow and works at runtime. A const assertion is recursive but exists only in the type system.
const grid = [
[1, 2],
[3, 4],
] as const;
// grid[0].push(5);
// error: Property 'push' does not exist on type 'readonly [1, 2]'.Spreading one tuple into another
You can spread a const tuple into a new as const literal. The elements are spliced into the new tuple's type in order.
const base = ["id", 1] as const;
const extended = [...base, true] as const;
// readonly ["id", 1, true]The spread has to be inside a literal that carries its own as const. Without it, the result is an ordinary widened array.
The empty literal
An empty array literal with as const is a tuple with no elements.
const none = [] as const; // readonly []It is rarely useful on its own. It shows up when a literal is built conditionally or generated.
Returning tuples from functions
Functions that return several values as an array benefit from as const. Without it, the return type is an array of the element union, and callers lose the per-position types. This is the pattern behind hook-style APIs.
function minMax(values: readonly number[]) {
return [Math.min(...values), Math.max(...values)] as const;
}
const [lo, hi] = minMax([3, 1, 2]);
// minMax returns readonly [number, number]
// lo: number, hi: numberHere the elements are not literal types, because Math.min(...) returns number. The tuple structure is still preserved: two elements, both numbers, in a fixed order. Compare the version without the assertion.
function minMaxLoose(values: readonly number[]) {
return [Math.min(...values), Math.max(...values)];
}
// returns number[]That version has the same element type but no length guarantee. For a mixed result such as [value, error], the assertion matters more. Without it you get (Value | Error)[], and every caller has to narrow each element separately.
function parsePort(input: string) {
const port = Number(input);
return Number.isInteger(port)
? ([port, null] as const)
: ([0, new Error("not an integer")] as const);
}
const [port, error] = parsePort("8080");
// port: 0 | number, error: Error | nullThe two branches produce different tuple types. The union of those tuples is what the caller receives, so port and error stay correlated at the type level only if you narrow on the tuple itself, not on the destructured variables. Narrowing destructured variables does not narrow their sibling in older compilers, so check your TypeScript version before relying on it.
Typing the elements you read back
A const tuple works well as a source of types. Chapter 5 covers deriving unions in depth. The essential idea is that indexing the tuple type with number produces the union of its elements.
const ROLES = ["admin", "editor", "viewer"] as const;
type Role = (typeof ROLES)[number];
// "admin" | "editor" | "viewer"
type First = (typeof ROLES)[0];
// "admin"The literal at runtime and the type in the compiler can never drift apart, because the type comes from the value.
The `includes` gotcha
Readonly tuple methods are typed against the literal union, not against string. That is correct for safety, but it breaks the most common use of such a list: checking an arbitrary input.
const ROLES = ["admin", "editor", "viewer"] as const;
function hasAccess(input: string): boolean {
// return ROLES.includes(input);
// error: Argument of type 'string' is not assignable to parameter of type '"admin" | "editor" | "viewer"'.
return (ROLES as readonly string[]).includes(input);
}The cast widens the view of the same array to readonly string[], which is a safe direction to widen. The cast does not change the runtime value. You can wrap it once in a type guard, as the earlier isRole example did, so the cast lives in one place.
const ROLES = ["admin", "editor", "viewer"] as const;
type Role = (typeof ROLES)[number];
function isRole(value: string): value is Role {
return (ROLES as readonly string[]).includes(value);
}
function describe(input: string): string {
if (isRole(input)) {
return `Known role: ${input}`; // input: Role
}
return "Unknown role";
}Common mistakes
- Expecting mutation to work. After
as const,push,pop,splice,sort, andreverseno longer exist on the type. If you need to build the array up, start from a normal array and add the assertion only to the final fixed data. - Passing a const tuple to a function that takes
T[]. A readonly array isn't assignable to a mutable one, because the callee could mutate it. The fix is to declare the parameter asreadonly T[]when the function only reads. The next chapter, "Passing readonly values to functions", covers this in detail. - Treating
as constas runtime protection. The assertion exists only at compile time. Another chapter shows that casting it away, or JavaScript callers, can still change the array. - Using it on a non-literal. An expression like
getList() as constis rejected, because a const assertion needs a literal to apply to. That restriction gets its own treatment in "Whatas constcannot do". - Forgetting that precision has a cost. A tuple type like
readonly ["id", 1, true]is exact, so two arrays with different contents have incompatible types. A long literal list produces a long type in error messages and in editor hover text.
Putting it together
This example combines the main features of the chapter. It defines a table of columns as a const tuple, derives a type for the column keys, and reads the data with full positional types.
const COLUMNS = [
{ key: "id", label: "ID" },
{ key: "name", label: "Name" },
{ key: "email", label: "Email" },
] as const;
type ColumnKey = (typeof COLUMNS)[number]["key"];
// "id" | "name" | "email"
type Row = Record<ColumnKey, string>;
function renderRow(row: Row): string {
return COLUMNS.map((column) => row[column.key]).join(" | ");
}
const header = COLUMNS.map((column) => column.label).join(" | ");
console.log(header);
console.log(renderRow({ id: "1", name: "Ada", email: "[email protected]" }));Three things are worth noticing:
row[column.key]type-checks.column.keyhas the type"id" | "name" | "email", which are exactly the keys ofRow. If you add a column,ColumnKeyandRowupdate automatically andrenderRowcallers must supply the new field.COLUMNS.map(...)works becausemapis available on readonly arrays.- Nothing is written twice. The runtime list is the only source for the labels and the keys.
Exercise
Given const point = [10, 20] as const;, what is the type of point, what is the type of point.length, and does point[2] compile?
Show answer
The type is readonly [10, 20]. point.length has the type 2. point[2] does not compile, because the tuple has length 2 and no element at index 2.
Exercise
You write const SIZES = ["sm", "md", "lg"] as const; and a function isSize(value: string) that returns SIZES.includes(value). Why does this not compile, and how do you fix it while keeping the return type a type guard value is Size?
Show answer
includes on readonly ["sm", "md", "lg"] only accepts "sm" | "md" | "lg", so a plain string argument is rejected. Define type Size = (typeof SIZES)[number]; and write function isSize(value: string): value is Size { return (SIZES as readonly string[]).includes(value); }. The cast widens the view to readonly string[], which is safe, and the type guard returns the narrowed type to the caller.
Exercise
What is the difference between const a: [string, number] = ["id", 1]; and const b = ["id", 1] as const;? Name one thing each can do that the other cannot.
Show answer
a has type [string, number]: the shape is fixed but the values are any string and any number, and the tuple is mutable, so a[0] = "name" compiles. b has type readonly ["id", 1]: the exact literal values are in the type, so you can derive "id" from it, but b[0] = "name" is an error because the tuple is read-only.