Mapped type for readonly fields in TypeScript
12 A mapped type that freezes every field
hardBuild a type that takes an object type and returns the same shape with every property read-only. Show that assignment is refused, and note what it does not protect.
Stuck? Three hints, smallest first
- 1. The modifier is
readonlyin front of the key:{ readonly [K in keyof T]: T[K] }. - 2. This is checked at compile time only. Nothing is frozen at runtime unless you call
Object.freeze. - 3. It is also shallow: a nested object’s own fields stay writable.
const same = (a: unknown, b: unknown): boolean =>
JSON.stringify(a) === JSON.stringify(b);
function test(name: string, got: unknown, want: unknown): void {
console.log(
(same(got, want) ? 'ok ' : 'FAIL ') + name +
(same(got, want) ? '' : ` got ${JSON.stringify(got)}, want ${JSON.stringify(want)}`)
);
}
type Seat = {
row: string;
number: number;
meta: { checkedIn: boolean };
};
type Frozen<T> = { readonly [K in keyof T]: T[K] };
const seat: Frozen<Seat> = { row: 'D', number: 12, meta: { checkedIn: false } };
// Each of these is a compile error:
// seat.row = 'E'; // Cannot assign to 'row' because it is a read-only property.
// seat.number = 13; // same
// But it is SHALLOW. The nested object is still open:
seat.meta.checkedIn = true;
// And it is compile-time only. Runtime freezing is a separate call:
const reallyFrozen = Object.freeze({ row: 'D', number: 12 });
let threw = false;
try {
// In strict mode, which every module is, this throws.
(reallyFrozen as { row: string }).row = 'E';
} catch { threw = true; }
console.log('nested field was changed:', seat.meta.checkedIn);
console.log('runtime write threw :', threw);
console.log('built-in equivalent :', Object.keys({} as Readonly<Seat>).length);
test('the readonly fields still read fine', seat.row, 'D');
test('readonly is shallow, nested changed', seat.meta.checkedIn, true);
test('Object.freeze does refuse at runtime', threw, true);
test('and the frozen value is unchanged', reallyFrozen.row, 'D');
Output
Two limits worth carrying away. readonly is compile-time only: it disappears from the output, so nothing stops a plain JavaScript caller writing to the field. And it is shallow, which is why seat.meta.checkedIn = true sails through. For a real guarantee you need Object.freeze as well, and even that is shallow. The built-in name for this type is Readonly<T>.