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

Create a free account to save this page, take notes and track your progress. Sign in

Syntax

Readonly<Type>

Parameters

ParameterDescription
Type The object type to transform.

Return value

A type whose properties are readonly.

Examples

Freeze an object's shapeTry it yourself
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 }
readonly arraysTry it yourself
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

VersionChange
TypeScript 2.1Added

Was this page helpful?