← 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.
Ctrl+Enter uruchamia testy. Tab robi wcięcie; aby wyjść z edytora klawiaturą, naciśnij Esc, a potem Tab. Kod zapisuje się w tej przeglądarce.
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.
- typy
type Config = { server: { port: number; tls: { cert: string } } }; type _ = Expect<Equal<DeepReadonly<Config>, { readonly server: { readonly port: number; readonly tls: { readonly cert: string } } }>>;
- typy
type State = { items: { id: number }[] }; type _ = Expect<Equal<DeepReadonly<State>, { readonly items: readonly { readonly id: number }[] }>>;
- typy
type Api = { load: (id: number) => string }; type _ = Expect<Equal<DeepReadonly<Api>, { readonly load: (id: number) => string }>>;
- typy
type _ = Expect<Equal<DeepReadonly<string>, string>>; - typy
const c = {} as DeepReadonly<{ a: { b: number } }>; // @ts-expect-error - nested fields are readonly too c.a.b = 2;