Exhaustive Record Covers Every Union Key
Type a lookup table as Record over a union so a missing or extra plan is a compile error, and derive the key list from the table instead of retyping it.
Code
type Plan = 'free' | 'pro' | 'team';
// Record 以联合类型(union)作键:少写一个键都无法通过编译
const PRICE_CENTS: Record<Plan, number> = {
free: 0,
pro: 900,
team: 2900,
};
function monthlyCents(plan: Plan): number {
return PRICE_CENTS[plan];
}
function allPlans(): Plan[] {
// 键全集直接由 Record 派生,Plan 新增成员而漏改这里会立刻报错
return Object.keys(PRICE_CENTS) as Plan[];
}
for (const plan of allPlans()) {
console.log(`${plan}: $${(monthlyCents(plan) / 100).toFixed(2)}`);
}
type NextPlan = Plan | 'enterprise';
// 需求演进:新表补齐新键
const NEXT_PRICES: Record<NextPlan, number> = {
...PRICE_CENTS,
enterprise: 9900,
};
// 旧表欠键会被编译拒绝(TS2739)
// @ts-expect-error: missing 'enterprise' key
const STALE: Record<NextPlan, number> = { ...PRICE_CENTS };
console.log('enterprise:', NEXT_PRICES.enterprise);
console.log('stale object still runs:', STALE.free);How it works
Exhaustive Record Covers Every Union Key is built around the functions monthlyCents and allPlans.
Repetition is confined to for (const plan of allPlans()) — the rest of the file is straight-line.
Putting it to use
Signature: function monthlyCents(plan: Plan)
Look for the enterprise:, stale object still runs: prefixes when the file runs; they tie each line to its step.
Core lines
return Object.keys(PRICE_CENTS) as Plan[];
return PRICE_CENTS[plan];
Interactive Tools for This Topic
FAQ
- Is a package install part of the setup?
- No. Installation is unnecessary because only built-in APIs are used. The file defines `monthlyCents`, `allPlans` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.