QuickSnip LogoA light blue logo with a thunderbolt in bracketsQuickSnip

Deep Readonly Type

Converts all properties of a type, including nested objects, into readonly.

  • helper-types
  • typedefinition
  • readonly

Install

npx shadcn@latest add https://quicksnip.dev/r/deep-readonly-type.json

This snippet is not verified yet. Review it before use, or help verify it.

Code

type DeepReadonly<T> = {
    readonly [K in keyof T]: T[K] extends object ? DeepReadonly<T[K]> : T[K];
};

Usage

type A = {
    name: string;
    details: {
        age: number;
        address: { city: string; zip: string };
    };
};

type ReadonlyA = DeepReadonly<A>;
/*
Type ReadonlyA:
{
  readonly name: string;
  readonly details: {
    readonly age: number;
    readonly address: { readonly city: string; readonly zip: string };
  };
}