DEV Community

Dharan Ganesan
Dharan Ganesan

Posted on

Day 53: Deep Readonly

Question

Create a type that makes all properties of a deeply nested object readonly, you can use TypeScript's recursive conditional types. Here's an example of how to define such a type.

type DeepReadonly<T> =  // Todo add your code here

// Example usage

interface Person {
  name: string;
  age: number;
  address: {
    street: string;
    city: string;
  };
}

type ReadonlyPerson = DeepReadonly<Person>;

const person: ReadonlyPerson = {
  name: 'John',
  age: 30,
  address: {
    street: '123 Main St',
    city: 'Exampleville',
  },
};

// This will result in a TypeScript error because properties are readonly:
// person.name = 'Alice';
// person.address.street = '456 Elm St';
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
dhrn profile image
Dharan Ganesan
type DeepReadonly<T> = {
  readonly [K in keyof T]: T[K] extends object ? DeepReadonly<T[K]> : T[K];
};

// Example usage

interface Person {
  name: string;
  age: number;
  address: {
    street: string;
    city: string;
  };
}


const person: DeepReadonly<Person> = {
  name: 'John',
  age: 30,
  address: {
    street: '123 Main St',
    city: 'Exampleville',
  },
};

// person.name = 'Alice';
// person.address.street = '456 Elm St';
Enter fullscreen mode Exit fullscreen mode