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.

TypescriptConfig Management

Code

snippet
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,maxAttempts

Stepwise 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

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.