Back to digital garden
TypeScript

Advanced TypeScript Utility Patterns

Compact snippet for creating deeply immutable types and type-safe key transformations.

When building robust design systems or API clients, you often need deep immutability:

type DeepReadonly<T> = T extends Function | boolean | number | string | null | undefined
  ? T
  : T extends Array<infer U>
    ? ReadonlyArray<DeepReadonly<U>>
    : T extends Map<infer K, infer V>
      ? ReadonlyMap<DeepReadonly<K>, DeepReadonly<V>>
      : T extends Set<infer M>
        ? ReadonlySet<DeepReadonly<M>>
        : { readonly [P in keyof T]: DeepReadonly<T[P]> };

This prevents accidental mutation in deeply nested configuration objects.