TypeScript 7 reference · Utility Types
TypeScript Readonly<Type> Utility Type
Make every property of a type read-only, so the compiler rejects assignments to them after creation.
TypeScript 7 Since 2.1
Syntax
Readonly<Type>
Parameters
| Parameter | Description |
|---|---|
Type |
The object type to transform. |
Return value
A type whose properties are readonly.
Examples
interface Point {
x: number;
y: number;
}
const origin: Readonly<Point> = { x: 0, y: 0 };
// @ts-expect-error: cannot assign to x, it is read-only
origin.x = 5;
console.log(origin);
Output
{ x: 5, y: 0 }function total(prices: readonly number[]): number {
// @ts-expect-error: push does not exist on a readonly array
prices.push(0);
return prices.reduce((a, b) => a + b, 0);
}
console.log(total([10, 20]));
Output
30
Readonly is checked at compile time only; at runtime the object can still be changed. Use Object.freeze() for runtime protection. Like Partial, it's shallow.
Version history
| Version | Change |
|---|---|
| TypeScript 2.1 | Added |
Related
Partial<Type>· Make every property of a type optional. Useful for update functions that accept only the fields that change.as const· Make a value deeply read-only with literal types: strings stay 'admin' instead of string, arrays become readonly tuples.- TypeScript Utility Types · tutorial