Search code examples
typescript

type-challenges:Why this answer couldn't pass all cases?


Recently I am interested in type challenges.Today I plan to solve 9.Deep Readonly problem. Problem My answer is just like this.

type DeepReadonly<T> = {
  readonly [K in keyof T]: T[K] extends Object ? DeepReadonly<T[K]> : T[K];
}

type-challenges' link

Why this answer couldn't pass all cases?Who could give an right answer?


Solution

  • functions also extend the object type, so checking against the object type is too broad and would be running any methods through DeepNested. So if we handle the function case first we can return it's type before we check for an object type.

    type DeepReadonly<T> = {
      readonly [Key in keyof T]: T[Key] extends Function
        ? T[Key]
        : T[Key] extends object
        ? DeepReadonly<T[Key]>
        : T[Key];
    };