DeepRequired Forces Nested Optional Keys

Recursively strip optional modifiers with a DeepRequired utility so nested configuration objects must provide every key at every level.

TypescriptConfig Management

Code

typescriptsnippet
34 lines
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,tls

Applying 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

FAQ

Will the snippet run without installing packages?
Yes, it runs as-is — nothing outside the built-in APIs is referenced.