Day 53: Deep Readonly

Dharan Ganesan - Sep 21 '23 - - Dev Community

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
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player