Deep Readonly Configuration Type

Make a nested configuration object deeply readonly so accidental mutation of shared settings fails at compile time rather than at runtime.

TypescriptConfig Management

Code

typescriptsnippet
24 lines
export type DeepReadonly<T> = {
  readonly [K in keyof T]: T[K] extends (infer U)[]
    ? readonly DeepReadonly<U>[]
    : T[K] extends object
      ? DeepReadonly<T[K]>
      : T[K];
};

export interface ServerConfig {
  port: number;
  db: { host: string; pool: { min: number; max: number } };
  features: string[];
}

export function freeze<T>(value: T): DeepReadonly<T> {
  const deepFreeze = (node: unknown): void => {
    if (node && typeof node === "object") {
      Object.values(node as Record<string, unknown>).forEach(deepFreeze);
      Object.freeze(node);
    }
  };
  deepFreeze(value);
  return value as DeepReadonly<T>;
}

How the snippet works

Deep Readonly Configuration Type keeps everything in the functions deepFreeze and freeze.

Applying it

The surface worth importing is freeze; the helpers around it are private to the snippet.

Statements that matter

readonly [K in keyof T]: T[K] extends (infer U)[]
  ? readonly DeepReadonly<U>[]
  : T[K] extends object
    ? DeepReadonly<T[K]>
    : T[K];
const deepFreeze = (node: unknown): void => {
  if (node && typeof node === "object") {
    Object.values(node as Record<string, unknown>).forEach(deepFreeze);
    Object.freeze(node);
  }
};
return value as DeepReadonly<T>;

Interactive Tools for This Topic

FAQ

Are there any imports to resolve outside the language?
No. Every import resolves against the language's own modules. The file defines `deepFreeze`, `freeze` at load time.