TypeScript Reference ยท Utility Types
TypeScript Readonly<T> utility type
Reference for TypeScript Readonly<T>: make every property read-only at compile time, why it is shallow, and how it differs from Object.freeze and as const.
Readonly<T> produces a type with the same properties as T, but every property is marked readonly. The compiler then rejects any assignment to those properties. It is the quickest way to say "this object must not be changed after it is built".
The restriction exists only in the type system. At runtime nothing is frozen, so use Object.freeze as well if you need real protection.
interface Account { id: number; owner: string; } const acc: Readonly<Account> = { id: 1, owner: "Mia" }; // acc.owner = "Zed"; // error: cannot assign to 'owner'
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.
Syntax
type Readonly<T> = { readonly [P in keyof T]: T[P]; };
| Name | Description |
|---|---|
T |
The type to copy. Works on object types, tuples and arrays. |
Result: a mapped type where each property has the readonly modifier. Optional markers are kept.
Edge cases: applied to an array or tuple type, Readonly<string[]> becomes readonly string[], which has no push or pop.
Usage notes
- Shallow. Only the first level is read-only. Nested objects and arrays inside can still be mutated unless their own types are readonly. For deep protection, write a recursive mapped type (see Recursive Types).
- Compile-time only. The emitted JavaScript contains no trace of it. Combine with
Object.freezewhen untrusted code could write to the object. - Assignability is lenient. A
Readonly<T>value can still be assigned to a variable of the mutable typeT, because TypeScript does not treatreadonlyas part of type compatibility for properties. The compiler will not stop that alias from writing. - Remove it with a mapped type using
-readonly:{ -readonly [P in keyof T]: T[P] }. - Compared with
as const:as constmakes a literal deeply readonly and narrows values to literal types;Readonly<T>is a type you apply to a declared shape. - Function parameters: declaring a parameter as
Readonly<T>documents that the function will not modify the argument. - Available since TypeScript 2.1.