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.
Code
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
Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.Gitignore Template BuilderCompose clean .gitignore files by combining Node, Python, Go, Rust, Java, OS, IDE, and Docker presets with deduplication and custom rules.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.JSON to TOML ConverterTurn a JSON object into TOML, emitting nested objects as tables and arrays of objects as array-of-tables blocks.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.