🌊

DeepReadonlyやDeepNullableはts-essentialsを使おう

2022/10/03に公開

今までネストされたObjectプロパティを readonly にしたい場合は DeepReadonly とか自前で作ってました。

type Primitive = number | string | boolean | bigint | symbol | undefined | null;
type DeepReadonly<T> =  T extends Primitive 
 ? { readonly [K in keyof T]: T[K] }
 : { readonly [K in keyof T]: DeepReadonly<T[K]>}

type Result = DeepReadonly<{ a: { b: { c: [1, 2, 3] } } }>
// 以下のようになる
// type Result = {
//    readonly a: {
//        readonly b: {
//            readonly c: readonly [1, 2, 3];
//        };
//    };
// }

今まで知らなかったけど、以下のパッケージを入れた方が早かった。わざわざ型パズルして色々と悩んで作る必要なかった😅
https://github.com/ts-essentials/ts-essentials

他にも StrictOmitStrictExtract など便利なものもあるので、これで工数削減できるかと思います。

Discussion