← Alle AufgabenTypeScript · Senior

DeepReadonly<T>

Das eingebaute Readonly<T> schützt nur die erste Ebene: config.server.port = 1 kompiliert weiterhin. Schreib DeepReadonly<T>, das jedes Feld in beliebiger Tiefe readonly macht, einschließlich Arrays und ihrer Elemente.

Funktionen bleiben, wie sie sind, und Primitive (string, number...) kommen unverändert zurück.

Tests (5)

Typtests prüft der TypeScript-Compiler im strict-Modus. Expect<Equal<A, B>> besteht, wenn die Typen exakt gleich sind, und // @ts-expect-error, wenn die nächste Zeile nicht kompiliert. Der erste Start lädt den Compiler und dauert daher ein paar Sekunden.

  1. Typen
    type Config = { server: { port: number; tls: { cert: string } } };
    type _ = Expect<Equal<DeepReadonly<Config>, { readonly server: { readonly port: number; readonly tls: { readonly cert: string } } }>>;
  2. Typen
    type State = { items: { id: number }[] };
    type _ = Expect<Equal<DeepReadonly<State>, { readonly items: readonly { readonly id: number }[] }>>;
  3. Typen
    type Api = { load: (id: number) => string };
    type _ = Expect<Equal<DeepReadonly<Api>, { readonly load: (id: number) => string }>>;
  4. Typen
    type _ = Expect<Equal<DeepReadonly<string>, string>>;
  5. Typen
    const c = {} as DeepReadonly<{ a: { b: number } }>;
    // @ts-expect-error - nested fields are readonly too
    c.a.b = 2;