Skip to content

CodeNot attempted

Type challenge: Readonly and DeepReadonly

Difficulty: medium

Implement MyReadonly<T>, then DeepReadonly<T> that makes nested objects and arrays readonly too, while leaving functions callable and primitives unchanged.

Show reference solution
export type MyReadonly<T> = { readonly [P in keyof T]: T[P] };
export type DeepReadonly<T> = T extends (...args: any[]) => any
? T // leave functions callable
: T extends object
? { readonly [P in keyof T]: DeepReadonly<T[P]> } // arrays map to readonly arrays too
: T;
Loading editor…