Sub topic 7
Why readonly does not affect assignability
This chapter assumes you know interfaces and type aliases, union types, and how readonly and ? are declared. You should also know that readonly is shallow and that it exists only at compile time. Here we look at one consequence of that design: a readonly property does not stop a value from being assigned to a type that lacks the modifier.
The behavior
Assignability is the rule the compiler uses to decide whether a value of type S may be used where type T is expected. For object types, TypeScript compares property names and property types. It does not compare the readonly modifier.
interface Mutable {
x: number;
}
interface Frozen {
readonly x: number;
}
const f: Frozen = { x: 1 };
const m: Mutable = f; // allowed: readonly is ignored in this check
m.x = 2; // allowed: m is typed as mutable
console.log(f.x); // 2Both variables point to the same object. The Frozen type promised that nobody would write through the f reference. It did not promise that the object itself would never change. Once the same object is reachable through a mutable reference, the change is visible through f as well.
You can confirm that the compiler treats the two types as compatible in both directions with a conditional type.
type FrozenToMutable = Frozen extends Mutable ? true : false; // true
type MutableToFrozen = Mutable extends Frozen ? true : false; // trueWhat readonly actually means
A readonly modifier restricts the reference it is attached to. It blocks assignment through that property access path and nothing else. It is not a property of the object in memory, and it does not follow the object around. Read readonly x: number as "code that holds this type may not write x", not as "x never changes".
This explains why the aliasing example compiles. The compiler checks each reference by its own declared type. Reference f has no write permission, and reference m has one.
Why the language works this way
The behavior is deliberate. There are three main reasons.
- Structural typing compares shapes. Two types with the same property names and types are interchangeable. Adding modifiers to the comparison would make
{ x: number }and{ readonly x: number }distinct in ways that most code does not expect. - Existing code would break. Many JavaScript libraries and older TypeScript declarations take plain mutable object types but never write to them. If a
readonlyobject could not be passed to such a function, adoptingreadonlywould require rewriting every signature in the call chain first. - Mutability is hard to track soundly. Making
readonlyaffect assignability would need a rule for every place a value flows: generics, callbacks, index access, and spreads. The TypeScript team chose a simple check that catches direct writes and leaves aliasing to the programmer.
The cost is that readonly is an honor system between you and the compiler. It prevents accidental writes in the code you can see. It does not prove that a value is immutable.
A leak through a function parameter
The same rule applies when you call a function. A function parameter typed as mutable accepts a readonly argument.
interface Point {
x: number;
y: number;
}
function reset(p: Point): void {
p.x = 0;
p.y = 0;
}
const start: Readonly<Point> = { x: 10, y: 20 };
reset(start); // compiles without error
console.log(start.x, start.y); // 0 0Nothing in the call site warns you. The function signature says Point, so the compiler assumes the function may write, but it still allows the call. The Readonly<Point> annotation on start gave a false sense of safety.
The fix is to state the intent in the signature of the function that does not need to write.
function distanceFromOrigin(p: Readonly<Point>): number {
return Math.hypot(p.x, p.y);
}Now distanceFromOrigin promises not to write, and the compiler enforces that inside its body. Callers can pass mutable or readonly points. A function that does write, like reset, should keep its mutable parameter type. The compiler will not stop you from passing it a readonly value, so review such calls yourself.
The exception: arrays and tuples
Arrays behave differently from object properties. A readonly number[] is not assignable to number[].
const ro: readonly number[] = [1, 2, 3];
// const rw: number[] = ro;
// Error: The type 'readonly number[]' is 'readonly' and cannot be
// assigned to the mutable type 'number[]'.
const copy: number[] = [...ro]; // fine: a new array is created
copy.push(4);The reason is structural, not a special modifier check. The type readonly number[] (also written ReadonlyArray<number>) has no push, pop, splice, or sort methods. A number[] has all of them. A value without those methods cannot stand in for a type that requires them. The array case is therefore an ordinary missing-members error.
The reverse direction is allowed, because every number[] has all the members a readonly number[] needs.
function sum(xs: readonly number[]): number {
return xs.reduce((total, n) => total + n, 0);
}
const nums: number[] = [1, 2, 3];
console.log(sum(nums)); // 6Readonly tuples follow the same rule. A readonly [number, number] cannot be assigned to [number, number].
Arrays nested inside objects
Because array types are compared structurally, a readonly array stored in an object property still matters when the object is assigned.
interface Frozen {
readonly items: readonly string[];
}
interface Loose {
items: string[];
}
const a: Frozen = { items: ["a"] };
// const b: Loose = a;
// Error: The type 'readonly string[]' is 'readonly' and cannot be
// assigned to the mutable type 'string[]'.The property modifier readonly on items is ignored. The readonly on the array type is not. The compiler compares the property types readonly string[] and string[] and rejects the assignment.
The table summarizes the cases.
| From | To | Allowed? | Reason |
|---|---|---|---|
| `{ readonly x: number }` | `{ x: number }` | Yes | Property modifiers are not compared |
| `{ x: number }` | `{ readonly x: number }` | Yes | Mutable is always usable as readonly |
| `readonly number[]` | `number[]` | No | Missing `push`, `pop` and other methods |
| `number[]` | `readonly number[]` | Yes | The mutable type has every readonly member |
| `Readonly<{ tags: string[] }>` | `{ tags: string[] }` | Yes | Property `tags` has the same array type on both sides |
No runtime enforcement
The aliasing problem is made worse by the fact that readonly is erased when TypeScript compiles to JavaScript. The emitted code contains no check. If you need a value that cannot change at runtime, use Object.freeze.
"use strict";
const frozen = Object.freeze({ x: 1 }); // typed as Readonly<{ x: number }>
const alias: { x: number } = frozen; // still compiles
try {
alias.x = 2;
} catch (e) {
console.log(e instanceof TypeError); // true
}
console.log(frozen.x); // 1The runtime stops the write, not the compiler. In strict mode code, assigning to a frozen object's property throws a TypeError. In sloppy mode the assignment is silently ignored. Object.freeze is also shallow: nested objects stay writable unless you freeze them too.
Working with this in practice
You cannot change the assignability rule, so you work around it with habits and tools.
- Put
readonlyon parameters that you only read. This documents intent and lets the compiler check the function body. Preferreadonly T[]overT[]for array parameters, because arrays are the one case where the compiler also blocks callers from losing the modifier. - Return copies from public methods if callers must not mutate internal state. A
readonlyreturn type is a hint. A copy is a guarantee. - Freeze at trust boundaries when mutation would cause real damage, such as shared configuration. Combine
Object.freezewith aReadonlyorDeepReadonlytype so the compile-time and runtime views agree. - Use lint rules for what the compiler skips. The
@typescript-eslint/prefer-readonly-parameter-typesrule flags parameters that are not readonly, which pushes a codebase toward consistent declarations. It cannot detect aliasing either, so it supports the habits above instead of replacing them.
Edge cases to remember
- Class instances follow the same rule. An instance with a
readonly idfield is assignable to an interface that declaresid: stringwithout the modifier. - Generics keep the gap.
Readonly<T>is assignable toTfor object types, so a function with signature<T>(value: T) => Taccepts and returns readonly objects as if they were mutable. - Index signatures behave like properties.
{ readonly [key: string]: number }is assignable to{ [key: string]: number }. - Spread creates a mutable copy.
{ ...frozenObject }produces a new object whose properties are not readonly, which is why spread is the standard way to "update" readonly data.
Exercise
Given const a: { readonly n: number } = { n: 1 }; and const b: { n: number } = a;, does the second line compile? What does a.n print after b.n = 5;?
Show answer
Yes, it compiles, because the compiler does not compare the readonly modifier on object properties. a and b refer to the same object, so after b.n = 5 the value a.n is 5.
Exercise
Why does const rw: string[] = ro; fail when ro is readonly string[], even though the same kind of assignment succeeds for readonly object properties?
Show answer
readonly string[] is a different type from string[]. It lacks mutating methods such as push, pop and splice, so it is missing members that string[] requires. The failure is a structural mismatch of members, not a comparison of the readonly modifier.
Exercise
A function function clear(list: string[]): void { list.length = 0; } is called with a value declared as readonly string[]. Does this compile? Then rewrite the call so it works without changing clear.
Show answer
It does not compile, because readonly string[] is not assignable to string[]. One fix is to pass a copy: clear([...list]);. This clears only the copy, so the original stays intact, which is usually what you want for a readonly value.