Skip to content
jshacks.dev
TypeScript

The Readonly Utility Type in TypeScript, With Examples

Readonly marks every property of a type as read-only at compile time. See its errors, why it is shallow, how it differs from Object.freeze, and when to use it.

7 min read
Summarize in AI
Flat illustration of an editor window full of code, with the TypeScript, Vite and npm logos.

Readonly<T> takes a type and marks all of its properties as read-only, so the compiler rejects any assignment to them. It is a quick way to say "this object is not meant to change", and it documents intent at function boundaries, in configuration and in state that should only be replaced, never mutated. It is also easy to misunderstand. The protection exists only while the compiler is checking, it reaches only the top level of an object, and it does not behave quite like a runtime lock. This post covers how Readonly works, shows its exact errors, compares it with Object.freeze and as const, and gives patterns for using it well. The examples target TypeScript 6.x, and the reference is the Readonly entry in the utility types page.

The basic idea

Apply Readonly to an object type, and assignments to its properties stop compiling.

basic.tsTypeScript
interface User {
  id: number;
  name: string;
}

const user: Readonly<User> = { id: 1, name: "Ada" };

user.name = "Grace";
Text
basic.ts(8,6): error TS2540: Cannot assign to 'name' because it is a read-only property.

The error points at the property name in the assignment. Reading is unaffected, and so is creating a new object with different values. The type does not say the data never changes, only that this reference is not allowed to change it.

How it is defined

Like Partial and Required, Readonly is a mapped type in the standard library, with the readonly modifier added to every property.

my-readonly.tsTypeScript
type MyReadonly<T> = {
  readonly [P in keyof T]: T[P];
};

interface Point {
  x: number;
  y: number;
}

const p: MyReadonly<Point> = { x: 1, y: 2 };

console.log(p);
Text
{ x: 1, y: 2 }

Once you see the definition, the behavior is predictable. The mapping runs over the top-level keys, copies each property type unchanged, and adds the modifier. The inverse is a mapped type with -readonly, which removes the modifier. The handbook describes both in the mapped types page.

The protection is shallow

Only the first level of properties becomes read-only. A nested object or an array is still mutable through its own methods.

shallow.tsTypeScript
interface Team {
  name: string;
  members: string[];
}

const team: Readonly<Team> = { name: "Core", members: ["Ada"] };

team.members.push("Grace");
team.members = [];

console.log(team.members);
Text
shallow.ts(9,6): error TS2540: Cannot assign to 'members' because it is a read-only property.

The push call on line 8 compiles, and the reassignment on line 9 does not. If the program ran after fixing the second line, it would print [ 'Ada', 'Grace' ], because the array was mutated in place. To protect the array as well, type it as readonly string[], or write a recursive mapped type for a deep version.

deep.tsTypeScript
interface Team {
  name: string;
  members: readonly string[];
}

const team: Readonly<Team> = { name: "Core", members: ["Ada"] };

team.members.push("Grace");
Text
deep.ts(7,14): error TS2339: Property 'push' does not exist on type 'readonly string[]'.

A readonly string[] has no mutating methods in its type at all, so push, pop and sort do not exist on it. That is a stronger guard than the property modifier, and it applies to arrays through the type ReadonlyArray<T> as well.

Readonly arrays and function parameters

The best everyday use of readonly is on parameters. A function that only reads an array should say so, so callers can pass either a mutable or an immutable array.

params.tsTypeScript
function total(values: readonly number[]): number {
  let sum = 0;
  for (const value of values) {
    sum += value;
  }
  return sum;
}

const fixed: readonly number[] = [1, 2, 3];
const growing: number[] = [4, 5];

console.log(total(fixed), total(growing));
Text
6 9

Both calls work, because a mutable array can always be used where a read-only one is expected. The opposite direction is rejected, which protects functions that need to modify their input.

reverse.tsTypeScript
function clear(values: number[]): void {
  values.length = 0;
}

const fixed: readonly number[] = [1, 2, 3];
clear(fixed);
Text
reverse.ts(6,7): error TS4104: The type 'readonly number[]' is 'readonly' and cannot be assigned to the mutable type 'number[]'.

The rule of thumb is to accept readonly T[] for inputs that you only read, and to return plain T[] for new arrays you create. That keeps the signature honest and costs callers nothing.

A quirk: readonly properties are still assignable

One behavior surprises people. TypeScript does not consider readonly when it checks whether one object type can be assigned to another. A read-only object can be passed where a mutable one is expected.

quirk.tsTypeScript
interface Mutable {
  name: string;
}

function rename(target: Mutable): void {
  target.name = "changed";
}

const frozen: Readonly<Mutable> = { name: "original" };
rename(frozen);

console.log(frozen.name);
Text
changed

This compiles without error, which is a known gap in the type system, chosen to keep the language compatible with existing code. It means Readonly guards the places where you write to a property directly, but it does not follow the object through every function it reaches. For stronger protection at runtime, you need to freeze the object.

Readonly versus Object.freeze

Readonly is a compile-time annotation. It produces no JavaScript, and a value typed as Readonly<T> is an ordinary mutable object at runtime. Object.freeze is the runtime counterpart, and TypeScript types its result as Readonly<T>.

freeze.tsTypeScript
const config = Object.freeze({ mode: "dark", retries: 3 });

try {
  (config as { mode: string }).mode = "light";
} catch (error) {
  if (error instanceof Error) {
    console.log(error.message);
  }
}

console.log(config.mode);
Text
Cannot assign to read only property 'mode' of object '#<Object>'
dark

The assertion defeats the compiler, so the assignment compiles. At runtime, the frozen object refuses the write, and because ES modules run in strict mode, the failure throws a TypeError whose message is shown above. In non-strict scripts the write would be ignored silently. Using both gives you early errors in the editor and a hard stop at runtime. Note that Object.freeze is also shallow, so nested objects remain mutable unless you freeze them too.

Readonly and const assertions

A close relative is as const, which infers the narrowest, read-only type for a literal.

const.tsTypeScript
const settings = { mode: "dark", retries: 3 } as const;

type Settings = typeof settings;

const copy: Readonly<{ mode: string; retries: number }> = settings;

console.log(copy);
Text
{ mode: 'dark', retries: 3 }

The as const form makes the literal types exact, "dark" and 3, and every property read-only, with arrays becoming read-only tuples. Readonly<T> is the tool for a type you already have, and as const is the tool for a value you are writing. They also compose, as the last example shows, since the narrow read-only type is assignable to the wider Readonly one.

State that is replaced, not mutated

In UI code and reducers, state is often updated by creating a new object. Readonly makes accidental mutation a compile error.

reducer.tsTypeScript
interface CounterState {
  count: number;
}

function increment(state: Readonly<CounterState>): CounterState {
  state.count += 1;
  return state;
}
Text
reducer.ts(6,9): error TS2540: Cannot assign to 'count' because it is a read-only property.

The right version returns a new object.

reducer-fixed.tsTypeScript
interface CounterState {
  count: number;
}

function increment(state: Readonly<CounterState>): CounterState {
  return { ...state, count: state.count + 1 };
}

const before: CounterState = { count: 1 };
const after = increment(before);

console.log(before.count, after.count);
Text
1 2

The input is untouched and the output is a new value, which is the contract that equality checks and change detection rely on.

When not to use Readonly

Do not sprinkle Readonly on every type by reflex. It adds noise, and because of the assignability quirk and its shallow reach, it can give a false sense of safety. Use it where an immutability contract is real: function parameters that must not be modified, configuration shared between modules, and state that flows through reducers. For data that the same module builds up step by step, mutable types are simpler. When the guarantee has to hold at runtime, for example for constants exported from a library, add Object.freeze or a copy on the way out.

Readonly in public APIs

For libraries, Readonly communicates a promise to callers about what you will not do. A function that takes Readonly<Options> says it will not modify the object you pass in, so you can reuse that object elsewhere without defensive copies. A function that returns Readonly<State> says callers should not modify what they receive. Both promises are enforced by the compiler for the code that uses the types, even though a determined caller can bypass them with assertions.

Because the check is cheap and only affects the type, it is easy to add later. If you are unsure whether a parameter should be read-only, start with the read-only version. Relaxing a parameter from readonly T[] to T[] never breaks callers, while tightening it later can.

Share

Keep reading

Flat illustration of an editor window full of code, with the TypeScript, npm and Node.js logos.
TypeScript

Type Inference in TypeScript

TypeScript works out most types for you. Learn how inference treats let and const, arrays, return values and callbacks, and when to write a type yourself.

7 min read
Flat illustration of an editor window full of code, with the TypeScript, Node.js, npm, Vite and JavaScript logos.
TypeScript

What Is TypeScript, and Why Use It?

TypeScript adds static types to JavaScript and checks them before your code runs. Learn what it is, what it catches, what it costs and when to use it.

6 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.