DeepRequired Forces Nested Optional Keys
Recursively strip optional modifiers with a DeepRequired utility so nested configuration objects must provide every key at every level.
Code
type DeepRequired<T> = T extends (...args: never[]) => unknown
? T
: T extends readonly (infer U)[]
? Array<DeepRequired<U>>
: T extends object
? { [K in keyof T]-?: NonNullable<DeepRequired<T[K]>> }
: T;
interface Settings {
server?: {
host?: string;
port?: number;
tls?: { enabled?: boolean; cert?: string };
};
retries?: number;
}
type StrictSettings = DeepRequired<Settings>;
const strict: StrictSettings = {
server: {
host: 'localhost',
port: 8080,
tls: { enabled: false, cert: '' },
},
retries: 3,
};
console.log(strict.server.host + ':' + strict.server.port);
console.log('tls enabled:', strict.server.tls.enabled);
console.log('keys:', Object.keys(strict.server).join(','));
// 少一层可选键就会被编译器拒绝
// const broken: StrictSettings = { server: { host: 'x' } };Output
Captured from a sandboxed run of this snippet in the build pipeline.
localhost:8080
tls enabled: false
keys: host,port,tlsApplying it
Running the file prints labeled results such as tls enabled:, keys: — each operation’s effect is visible in the output.
Output is labeled for readability — expect lines prefixed with tls enabled:, keys:.
Statements that matter
? { [K in keyof T]-?: NonNullable<DeepRequired<T[K]>> }
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.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.JSON to YAML ConverterConvert JSON to readable YAML with nested block mappings, sequences, and quoting only where it is required.
FAQ
- Will the snippet run without installing packages?
- Yes, it runs as-is — nothing outside the built-in APIs is referenced.
Report a problem with this exampleOpens a pre-filled issue on GitHub.