← Wszystkie zadaniaTypeScript · Senior

DeepReadonly<T>

Wbudowany Readonly<T> chroni tylko pierwszy poziom: config.server.port = 1 nadal się kompiluje. Napisz DeepReadonly<T>, które robi readonly wszystkie pola na dowolnej głębokości, w tym tablice i ich elementy.

Funkcje zostają bez zmian, a typy proste (string, number...) wracają takie same.

Testy (5)

Testy typów sprawdza kompilator TypeScriptu w trybie strict. Expect<Equal<A, B>> przechodzi, gdy typy są dokładnie takie same, a // @ts-expect-error, gdy następna linia się nie kompiluje. Pierwsze uruchomienie pobiera kompilator, więc trwa kilka sekund.

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