Skip to content
Onsite

DeepReadonly<T>

MediumP1Coding

Implement DeepReadonly<T>.

It makes every property of T readonly, at every depth, through nested objects and arrays. Function types must be left unchanged. Primitives stay as they are.

Tests your type must pass

type X1 = {
  a: () => 22
  b: string
  c: {
    d: boolean
    e: {
      g: {
        h: {
          i: true
          j: 'string'
        }
        k: 'hello'
      }
      l: [
        'hi',
        {
          m: ['hey']
        },
      ]
    }
  }
}

type Expected1 = {
  readonly a: () => 22
  readonly b: string
  readonly c: {
    readonly d: boolean
    readonly e: {
      readonly g: {
        readonly h: {
          readonly i: true
          readonly j: 'string'
        }
        readonly k: 'hello'
      }
      readonly l: readonly [
        'hi',
        {
          readonly m: readonly ['hey']
        },
      ]
    }
  }
}

type Todo = DeepReadonly<{ a: number; b: string[] }>
declare const todo: Todo

type cases = [
  Expect<Equal<DeepReadonly<X1>, Expected1>>,
  Expect<Equal<DeepReadonly<number>, number>>,
  Expect<Equal<DeepReadonly<() => void>, () => void>>,
]

// @ts-expect-error the nested array is readonly
todo.b.push('x')
// @ts-expect-error the property is readonly
todo.a = 2

Hints

TypeScript
Run and Submit type-check your solution against the tests.