Split Required And Optional Keys With Pick
Separate RequiredKeys<T> and OptionalKeys<T> using conditional mapped types over Pick<T, K>, then validate mandatory keys before merging config defaults.
Code
interface ServiceConfig {
host: string;
port: number;
retries?: number;
tls?: boolean;
}
// `{}` is assignable to `Pick<T, K>` only when property K is optional
type RequiredKeys<T> = {
[K in keyof T]-?: {} extends Pick<T, K> ? never : K;
}[keyof T];
type OptionalKeys<T> = {
[K in keyof T]-?: {} extends Pick<T, K> ? K : never;
}[keyof T];
type RequiredServiceKey = RequiredKeys<ServiceConfig>; // 'host' | 'port'
type OptionalServiceKey = OptionalKeys<ServiceConfig>; // 'retries' | 'tls'
const REQUIRED_KEYS: readonly RequiredServiceKey[] = ['host', 'port'];
const OPTIONAL_DEFAULTS: Required<Pick<ServiceConfig, OptionalServiceKey>> = {
retries: 3,
tls: true,
};
function resolveServiceConfig(raw: Record<string, unknown>): ServiceConfig {
for (const key of REQUIRED_KEYS) {
if (raw[key] === undefined) {
throw new Error(`Missing required config key: ${key}`);
}
}
return {
host: String(raw.host),
port: Number(raw.port),
retries: typeof raw.retries === 'number' ? raw.retries : OPTIONAL_DEFAULTS.retries,
tls: typeof raw.tls === 'boolean' ? raw.tls : OPTIONAL_DEFAULTS.tls,
};
}
console.log('resolved:', JSON.stringify(resolveServiceConfig({ host: 'db.internal', port: 5432 })));
try {
resolveServiceConfig({ host: 'db.internal' });
} catch (err) {
console.log('rejected:', (err as Error).message);
}Output
Captured from a sandboxed run of this snippet in the build pipeline.
resolved: {"host":"db.internal","port":5432,"retries":3,"tls":true}
rejected: Missing required config key: portExecution walkthrough — Split Required And Optional Keys With Pick
Structurally, expect the function resolveServiceConfig and nothing else.
Iteration happens inside for (const key of REQUIRED_KEYS) — everything outside it runs once. Invalid states are rejected up front: it throws Error instead of continuing with bad data.
The result comes back as an object carrying retries, tls.
What to watch for
- Nothing arrives from a registry; the language ships every API used.
- The guard
raw[key] === undefinedstops downstream steps promptly through an upfrontthrowwhen its condition holds.
Using it
Signature: function resolveServiceConfig(raw: Record<string, unknown>)
The file’s steps show up in the output as resolved:, rejected:.
The call returns retries, tls — destructure what you need at the call site.
Key statements
throw new Error(`Missing required config key: ${key}`);
[K in keyof T]-?: {} extends Pick<T, K> ? never : K;
[K in keyof T]-?: {} extends Pick<T, K> ? K : never;
Interactive Tools for This Topic
FAQ
- Does `resolveServiceConfig` modify its input?
- No — a new value is constructed for the result and the arguments are never written to.
- What happens on invalid input?
- The code throws `Error` — the guard `raw[key] === undefined` rejects bad states before the main logic runs. Handle it at the call site or let it propagate deliberately.
- Are there dependencies to manage?
- No. There are no dependencies to declare or install. The file defines `resolveServiceConfig` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.