Reject Excess Keys On Generic Config Objects
Enforce exact object shapes on aliased variables in generic functions with Record<Exclude<keyof Input, keyof Shape>, never> so typos fail at compile time.
Code
interface RetryPolicy {
maxAttempts: number;
baseDelayMs: number;
}
// Excess keys map to `never`, so even aliased variables fail when they carry extra fields
type Exact<Shape, Input extends Shape> = Input &
Record<Exclude<keyof Input, keyof Shape>, never>;
function applyPolicy<const T extends RetryPolicy>(policy: Exact<RetryPolicy, T>): RetryPolicy {
return { maxAttempts: policy.maxAttempts, baseDelayMs: policy.baseDelayMs };
}
const cleanVar = { maxAttempts: 3, baseDelayMs: 250 };
const applied = applyPolicy(cleanVar);
console.log('applied:', applied.maxAttempts, applied.baseDelayMs);
// With an extra field on an aliased variable, `Exact` flags `retires: never` at compile time:
// const typoVar = { maxAttempts: 3, baseDelayMs: 250, retires: 5 };
// applyPolicy(typoVar);
const keys = Object.keys(applied).sort();
console.log('exact keys:', keys.join(','));Output
Captured from a sandboxed run of this snippet in the build pipeline.
applied: 3 250
exact keys: baseDelayMs,maxAttemptsStepwise trace — Reject Excess Keys On Generic Config Objects
The snippet is organized around the function applyPolicy.
The result comes back as an object carrying maxAttempts.
What to watch for
- Needs only out-of-the-box toolchain modules without grabbing external libraries.
Using it
The file’s steps show up in the output as applied:, exact keys:.
The call returns maxAttempts.
Key statements
return { maxAttempts: policy.maxAttempts, baseDelayMs: policy.baseDelayMs };
Record<Exclude<keyof Input, keyof Shape>, never>;
const keys = Object.keys(applied).sort();
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
- Does `applyPolicy` modify its input?
- It does not. Inputs are only read; the return value is freshly built.
- Does the runtime need any help from npm, pip, cargo, or the like?
- No — the package manager has nothing to do here; nothing is declared. The file defines `applyPolicy` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.