Sub topic 11
Readonly tuples and as const
This chapter covers how to make a tuple read-only and how as const turns an ordinary literal into a precise, immutable type. It assumes you know basic tuple types such as [number, string] and the readonly array modifier from the earlier chapters. It also assumes you know union types and literal types such as "admin".
Readonly tuples
You can put readonly in front of any tuple type. The tuple keeps its fixed length and per-position types, but the type no longer offers mutating operations.
const ro: readonly [number, string] = [1, "a"];
const n: number = ro[0];
const len: 2 = ro.length; // the length is the literal type 2
// ro[0] = 5; // Error: Cannot assign to '0' because it is a read-only property.
// ro.push(3); // Error: Property 'push' does not exist on type 'readonly [number, string]'.The built-in Readonly<T> utility gives the same result when T is a tuple, so Readonly<[number, string]> equals readonly [number, string].
Assignability goes one way
A mutable tuple can be used wherever a readonly tuple is expected. The reverse is an error, because the receiver could mutate something the sender promised was fixed.
function show(pair: readonly [number, string]): string {
return `${pair[0]}:${pair[1]}`;
}
function mutate(pair: [number, string]): void {
pair[0] = 99;
}
const mutable: [number, string] = [1, "a"];
const frozen: readonly [number, string] = [2, "b"];
show(mutable); // OK: mutable to readonly
show(frozen); // OK
mutate(mutable); // OK
// mutate(frozen); // Error: The type 'readonly [number, string]' is 'readonly'
// // and cannot be assigned to the mutable type '[number, string]'.This is why a function that only reads its argument should declare the parameter as readonly. Callers can then pass either kind. A mutable parameter type rejects readonly values.
Readonly is shallow
readonly applies only to the tuple itself. Objects and arrays stored inside it stay mutable.
const holder: readonly [number[], string] = [[1, 2], "x"];
holder[0].push(3); // compiles: the inner array is a normal number[]
// holder[0] = []; // Error: Cannot assign to '0' because it is a read-only property.Const assertions
A const assertion is the expression value as const. It tells the compiler to infer the narrowest, most immutable type for a literal. Without it, TypeScript widens literals so that they stay usable as mutable values.
const widened = [1, "a"]; // (string | number)[]
const fixed = [1, "a"] as const; // readonly [1, "a"]For an array literal, as const has three effects:
- The array becomes a tuple, so length and positions are fixed.
- The tuple becomes
readonly. - Each element gets its literal type (
1, notnumber).
For an object literal, every property becomes readonly and keeps its literal type. Nested arrays become readonly tuples, and nested objects are treated the same way, recursively.
const config = {
host: "localhost",
ports: [80, 443],
tls: { enabled: true },
} as const;
// typeof config:
// {
// readonly host: "localhost";
// readonly ports: readonly [80, 443];
// readonly tls: { readonly enabled: true };
// }
// config.ports.push(8080); // Error: Property 'push' does not exist on type 'readonly [80, 443]'.
// config.host = "example.com"; // Error: Cannot assign to 'host' because it is a read-only property.Unlike a plain readonly annotation, as const goes deep. That is its main advantage for configuration data.
Where as const is allowed
A const assertion works only on literal expressions: string, number, boolean, array and object literals, and enum members. Applying it to a variable or a function call is a compile error.
const nums = [1, 2, 3];
// const frozen = nums as const;
// Error: A 'const' assertion can only be applied to references to enum members,
// or string, number, boolean, array, or object literals.
const frozenNums = [1, 2, 3] as const; // OK: applied to the literal itselfIt also has no effect at runtime. The compiled JavaScript is the same array, and nothing stops other code from mutating it. If you need real immutability at runtime, combine the type with Object.freeze, which freezes only the top level.
const point = Object.freeze([10, 20] as const);
// type: readonly [10, 20]Deriving types from a constant
The most common use of as const is to keep one list as the single source of truth for both values and types. Indexing a readonly tuple with number gives the union of its element types.
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);
}
const r: Role = "editor";
// const bad: Role = "owner"; // Error: Type '"owner"' is not assignable to type 'Role'.The cast in isRole is needed because includes on readonly ["admin", "editor", "viewer"] accepts only those three literals, not an arbitrary string. Widening the view to readonly string[] is safe here because the method only reads.
Without as const, ROLES would be string[] and Role would be plain string.
Returning tuples with as const
A function that returns an array literal is inferred as an array, not a tuple. Adding as const to the return value fixes that, so destructuring gets per-position types.
function parse(input: string) {
return [input.trim().length, input.trim()] as const;
}
// return type: readonly [number, string]
const [length, text] = parse(" hello ");
// length: number, text: stringHere the elements are not literals, so they keep the types number and string. Only literal expressions get narrowed.
The cost of this shortcut is the readonly result. If a caller needs to pass it to a function that takes a mutable [number, string], the call fails. For public APIs, an explicit return annotation such as [number, string] is often a better contract. For internal helpers, as const is shorter.
Checking a constant with satisfies
as const narrows the type but does not check it against anything. The satisfies operator (TypeScript 4.9 and later) validates the shape while keeping the narrow type.
const origin = [0, 0] as const satisfies readonly [number, number];
// type: readonly [0, 0]
// const wrong = [0, 0, 0] as const satisfies readonly [number, number];
// Error: Source has 3 element(s) but target allows only 2.Note the readonly in the target. A readonly tuple is not assignable to a mutable tuple type, so satisfies [number, number] would fail here.
Choosing between the options
| Goal | Tool | Resulting type for `[1, "a"]` | Column |
|---|---|---|---|
| Mutable array, widened | no annotation | `(string \ | number)[]` |
| Mutable tuple with general types | annotation `[number, string]` | `[number, string]` | |
| Immutable tuple with general types | annotation `readonly [number, string]` | `readonly [number, string]` | |
| Immutable tuple with literal types | `as const` | `readonly [1, "a"]` |
Common mistakes
- Passing an
as constvalue to a mutable parameter. The error mentions "readonly" and "mutable type". Change the parameter to a readonly type instead of casting the argument. - Expecting runtime protection. A const assertion is erased during compilation.
- Expecting a literal where the value is not a literal.
[Math.random()] as constisreadonly [number]. - Forgetting that
typeofneeds parentheses in indexed access for readability.typeof ROLES[number]parses correctly, but(typeof ROLES)[number]is clearer. - Assuming
readonlyis deep. Useas conston the literal, or a recursive readonly type, when nested data matters.
The diagram shows how the same literal ends up with different types depending on what you write around it.
Exercise
Given const levels = ["low", "mid", "high"] as const;, write a type Level that is the union of its elements. Then explain why const copy: string[] = levels; fails.
Show answer
type Level = (typeof levels)[number]; gives "low" | "mid" | "high". The assignment fails because levels has the type readonly ["low", "mid", "high"], and a readonly tuple is not assignable to the mutable type string[]. The target could call push or assign to an index, which the readonly source forbids. Typing the target as readonly string[] makes it compile.
Exercise
What are the types of a and b below, and does the last line compile?
const a = [1, 2] as const;
const b = [1, 2];
const total: number = a[0] + b[0];
const third = a[2];
Show answer
a is readonly [1, 2] and b is number[]. The total line compiles, because a[0] is the literal 1, which is a number, and b[0] is number. The third line is an error: "Tuple type 'readonly [1, 2]' of length '2' has no element at index '2'." The array b would allow b[2] without a compile error, since arrays do not track their length.