Skip to content

Implementing a Custom Utility Type: Readonly

Implement the built-in Readonly generic without using it.

Readonly is a utility type in TypeScript that allows you to create a new type by making all properties of an existing type readonly.

Syntax:

Readonly<Type>

Example

type User = {
  id: number;
  name: string;
  email: string;
  age: number;
};

type ReadonlyUser = Readonly<User>;

// Equivalent to:
type ReadonlyUser = {
  readonly id: number;
  readonly name: string;
  readonly email: string;
  readonly age: number;
};

// Usage
const user: ReadonlyUser = {
  id: 1,
  name: "John Doe",
  email: "john@example.com",
  age: 30,
};

Solution

The custom Readonly type uses a mapped type to iterate over all properties of the original type (T) and make them readonly.

type User = {
  id: number;
  name: string;
  email: string;
  age: number;
};

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

// Usage
type ReadonlyUser = MyReadonly<User>;

Summary

References