Record, Exclude, Extract, NonNullable
Record over a union of keys requires every key, Exclude removes union members, Extract keeps them and NonNullable drops null and undefined. Exclude and Extract are distributive conditional types that test each union member separately. So a map keyed by the full union does not build without a new currency, while one keyed by a plain string requires nothing and lies about missing keys.
TypeScript · Utility types
JPY was added to Currency, and the decimals map said nothing. How do we make the compiler demand every key?
A test utility converts an amount to the minor units of a currency. The map { UAH: 2, USD: 2, EUR: 2 } was written long ago, and Currency now also has JPY. The function returns NaN for yen, the test fails, and the compiler said nothing. This lesson is about four utilities that turn unions and object types into "complete tables" and filters: Record, Exclude, Extract, NonNullable.
How it works and why. Record<K, V> is a mapped type over the keys K. If K is a union of literals, each member becomes a required key, so the map has to cover every variant. Exclude and Extract are conditional types that distribute over a union: the condition is checked for each member separately and the result is gathered back into a union. Since TypeScript 4.8, NonNullable is the intersection T & {}, which drops null and undefined. Simplified:
type Record<K extends keyof any, T> = { [P in K]: T };
type Exclude<T, U> = T extends U ? never : T;
type Extract<T, U> = T extends U ? T : never;
type NonNullable<T> = T & {};
What each utility keeps
Example: a map that does not notice a new currency. Typical code where the map was described as Record<string, number> because it is simpler:
type Currency = 'UAH' | 'USD' | 'EUR';
const minorUnits: Record<string, number> = {
UAH: 2,
USD: 2,
EUR: 2,
};
function toMinor(amount: number, c: Currency): number {
return Math.round(amount * 10 ** minorUnits[c]);
}
The key string accepts any set of keys, so neither adding JPY to Currency nor leaving it out of the map gives an error. The access minorUnits[c] returns undefined, 10 ** undefined is NaN, and Math.round also gives NaN. The types did not help because they promised "a number is always there".
The fix is to tie the map keys to the union: Record<Currency, number>. The satisfies operator checks completeness without changing the inferred type, and together with as const the values stay exact literals (2, 0) instead of widening to number:
type Currency = 'UAH' | 'USD' | 'EUR' | 'JPY';
const minorUnits = {
UAH: 2,
USD: 2,
EUR: 2,
JPY: 0,
} as const satisfies Record<Currency, number>;
function toMinor(amount: number, c: Currency): number {
return Math.round(amount * 10 ** minorUnits[c]);
}
Now deleting JPY from the map or adding a new currency without an entry is impossible: the compiler complains about the missing key. There is a domain benefit too: JPY has 0 decimal places while most currencies have 2 (ISO 4217 also has currencies with 3, such as KWD), so "all are 2" was a wrong assumption, not just a convenience.
A currency map
Record<string, number>
Any key passes. A new currency without an entry gives undefined and then NaN in calculations.
as const satisfies Record<Currency, number>
The compiler demands an entry for every currency, and the values stay exact literals.
Exclude, Extract and filtering a union. A helper that waits for a final status needs a type without PENDING:
type TxStatus = 'PENDING' | 'COMPLETED' | 'FAILED' | 'REVERSED';
type FinalStatus = Exclude<TxStatus, 'PENDING'>;
async function waitForStatus(
id: string,
expected: FinalStatus,
): Promise<void> {
await expect
.poll(() => api.getTransfer(id).then((t) => t.status))
.toBe(expected);
}
await waitForStatus(id, 'COMPLETED'); // ok
await waitForStatus(id, 'PENDING'); // compile error
A pointless test that waits for a "final" PENDING does not compile. Extract works with object types by assignability: Extract<AppEvent, { amount: number }> keeps the members assignable to that type, and picking by the discriminant is more reliable.
type AppEvent =
| { type: 'deposit'; amount: number }
| { type: 'withdrawal'; amount: number }
| { type: 'blocked'; reason: string };
type MoneyEvent = Extract<AppEvent, { amount: number }>;
type DepositEvent = Extract<AppEvent, { type: 'deposit' }>;
type NonBlocked = Exclude<AppEvent, { type: 'blocked' }>;
One more filter: NonNullable<string | null | undefined> is string. It describes a value after a check, for example the result of filter with a type guard.
Limits and alternatives.
Record<string, V>lies about missing keys: access givesVwhile at runtime it may beundefined. ThenoUncheckedIndexedAccessoption or the typePartial<Record<string, V>>helps. For dynamic keys aMapis sometimes better.ExcludeandExtractchange only the type, not values. If a union is written by hand apart from the API, it can lag behind the server: types do not know the backend added a status.- To walk the keys of a
Recordyou needObject.keys, which returnsstring[], notkeyof T: an explicit cast or anas constarray is needed.
Common mistakes.
Record<string, V>where the keys are known: the map does not demand completeness.- An annotation
: Record<Currency, number>instead ofas const satisfieswhen exact literal values are needed: they widen tonumber. - Picking union members with
Extractby an arbitrary shape when a discriminant exists: variants that are assignable by accident get into the selection. - Thinking
NonNullablealso removes empty strings or zero: onlynullandundefined.
Check yourself
The map const m: Record<string, number> = { UAH: 2, USD: 2 } compiles, and m['EUR'] returns undefined. What should change so that EUR without an entry does not build?
Answer
Tie the keys to the union: Record<Currency, number> (better via as const satisfies to keep the exact values). Then a missing key is a compile error.
What type does Exclude<'A' | 'B' | 'C', 'B'> give, and why does it work for each member separately?
Answer
It is 'A' | 'C'. Exclude<T, U> is T extends U ? never : T, and a conditional type distributes over a union: each member is checked, and those that fit U become never and vanish from the result.
Record with a union of keys requires every key, so a map covers all variants, for example all currencies. Exclude and Extract filter a union. Middle/Senior: Exclude and Extract are distributive conditional types, and Record<string, V> demands nothing and lies about missing keys, so for known keys I use satisfies Record<Union, V>, and for dynamic ones I turn on noUncheckedIndexedAccess.