Question

Implement the built-in Readonly<T> generic without using it.
Constructs a type with all properties of T set to readonly, meaning the properties of the constructed type cannot be reassigned.
For example

  1. interface Todo {
  2. title: string
  3. description: string
  4. }
  5. const todo: MyReadonly<Todo> = {
  6. title: "Hey",
  7. description: "foobar"
  8. }
  9. todo.title = "Hello" // Error: cannot reassign a readonly property
  10. todo.description = "barFoo" // Error: cannot reassign a readonly property

Answer

  1. type MyReadonly<T> = {
  2. readonly [P in keyof T]: T[P]
  3. }