Mapped types and conditional types
A mapped type walks over the keys of keyof T to build a new type, and a conditional type is an if at the type level. This derives one type from a model, so two descriptions cannot drift apart: Partial, Readonly, Exclude and Extract are built this way. Complex types give complex errors, so they stay in the framework layer and tests use simpler ones.
TypeScript · Advanced types
The holds field was added to Balance, and getHolds in BalanceApi was forgotten. How do we make a type follow the model?
The model Balance has three fields, and the client interface BalanceApi is written by hand with a method per field. holds was added and nobody wrote a method for it: the compiler did not notice, because the two descriptions are linked only by human attention. This lesson covers mapped types and conditional types: how to build a type from another one, what they rest on, and where the limit is beyond which the code becomes unreadable.
How it works and why. A mapped type walks over keys and builds a new type: { [K in keyof T]: … }. This is how Partial, Readonly and Record are made. Modifiers change properties: ? adds and -? removes optionality, readonly and -readonly do the same for immutability. A mapped type over keyof T keeps the modifiers of the source type, so its "homomorphism" gives a predictable result. Since TypeScript 4.1 keys can be renamed with as.
type Nullable<T> = { [K in keyof T]: T[K] | null };
type Concrete<T> = { [K in keyof T]-?: T[K] };
type Mutable<T> = { -readonly [K in keyof T]: T[K] };
A conditional type is an "if" at the type level: T extends U ? X : Y. Together with infer it extracts part of a type: "substitute whatever is there". The key property is called distributivity: if T is a "naked" type parameter and a union is passed, the condition is applied to each member separately and the results are gathered into a union. This is how Exclude and Extract work.
Distribution over a union
Example: two descriptions that drift. A model and a hand-written interface:
interface Balance {
available: number;
blocked: number;
holds: number;
}
interface BalanceApi {
getAvailable(): Promise<number>;
getBlocked(): Promise<number>;
}
The method getHolds is missing and nothing demands it. The interface that was supposed to be a "mirror" of the model became a second source of truth.
The fix: derive the client type from the model with a mapped type that renames keys.
type Getters<T> = {
[K in keyof T as `get${Capitalize<string & K>}`]: () => Promise<T[K]>;
};
type BalanceApi = Getters<Balance>;
function makeBalanceApi(id: string): BalanceApi {
return {
getAvailable: () => fetchField(id, 'available'),
getBlocked: () => fetchField(id, 'blocked'),
getHolds: () => fetchField(id, 'holds'),
};
}
Here keyof T as … renames the key available to getAvailable (the template and Capitalize are covered in the lesson on template literal types), and the value becomes a function returning a promise of the field type. If another field is added to Balance, makeBalanceApi stops compiling until the method appears. The same happens if a method is removed.
Extracting a type with infer. A conditional type is needed when one type depends on another:
type ApiResult<D> =
| { status: 'success'; data: D }
| { status: 'error'; message: string };
type DataOf<T> = T extends { status: 'success'; data: infer D } ? D : never;
type ItemOf<T> = T extends readonly (infer I)[] ? I : never;
type A = DataOf<ApiResult<Account>>; // Account
type B = ItemOf<Transaction[]>; // Transaction
DataOf distributes over the union ApiResult: for the success member it returns data, for error it returns never, which vanishes from the union. The result is a clean Account.
T extends U and [T] extends [U]
T extends U ? …
A naked parameter: each union member is checked separately. For never the result is never.
[T] extends [U] ? …
The parameter in a tuple: the union is considered whole. For never the condition holds.
How to switch distribution off and why it sometimes matters:
type ToArray<T> = T extends unknown ? T[] : never;
type R1 = ToArray<string | number>; // string[] | number[]
type ToArrayWhole<T> = [T] extends [unknown] ? T[] : never;
type R2 = ToArrayWhole<string | number>; // (string | number)[]
type IsNeverBad<T> = T extends never ? true : false; // gives never for never
type IsNever<T> = [T] extends [never] ? true : false; // gives true for never
The check for never is telling: never is an empty union, so a distributive condition has nobody to check and returns never, while the tuple wrapper gives the expected true.
Limits and alternatives.
- In tests such types are written rarely. They are needed in the framework layer: a typed API client, factory generators, wrappers. In a test, simpler types are better.
- A complex type gives complex error messages. If a colleague cannot read a type, it is simplified or given a name with a comment.
- Deep recursion in types has a limit, and large unions slow the compiler: a nice idea of a five-level
DeepPartialcan hit build time. - When the shape is known in advance, it is sometimes simpler to write an interface by hand or generate it from OpenAPI than to build it in types.
Common mistakes.
- Mixing up distributive and non-distributive conditions:
IsNever<never>without a tuple givesnever. - Mapping over
keyof Twhen a list of keys without modifiers is needed: a homomorphic mapped type keeps?andreadonly. - Over-complicating types in tests where an interface would do.
- Renaming keys with
aswithoutstring & K: keys may be numbers or symbols.
Check yourself
A holds field was added to Balance. Why does BalanceApi = Getters<Balance> force a method to be added while a hand-written interface does not?
Answer
The mapped type builds keys from keyof Balance, so the type of the new method appears at once and an implementation without it does not build. A hand-written interface is not linked to the model, so nobody checks the drift.
Why does type IsNever<T> = T extends never ? true : false give never for IsNever<never>, and how is it fixed?
Answer
The condition is distributive and never is an empty union: there is nobody to check, so the result is never. Wrap both sides in a tuple: [T] extends [never] ? true : false.
keyof T and builds a new type, which is how Partial and Readonly are made. A conditional type is a condition at the type level, and with infer you can extract, for example, the element type of an array. Middle/Senior: I know about distributivity ([T] extends [U] switches it off) and use all this sparingly, mostly in the library layer: a typed client, factories. A complex type that a colleague cannot read I simplify.