Sub topic 3
Mapped Types and Conditional Types
Assume you know basic TypeScript types, interfaces, type aliases, functions, unions, and classes.
Mapped Types
A mapped type creates a new type by iterating over the keys of another type.
interface User {
id: number;
name: string;
active: boolean;
}
type ReadonlyUser = {
readonly [K in keyof User]: User[K];
};
const user: ReadonlyUser = { id: 1, name: "Ada", active: true };keyof User produces the keys "id" | "name" | "active". The mapped type keeps each property type while adding readonly.
Built-in Utility Types
TypeScript provides common mapped types:
Partial<T>makes every property optional.Pick<T, K>keeps only selected keys.Record<K, V>creates properties for keysK, all with value typeV.ReturnType<F>extracts a function's return type.
type UserDraft = Partial<User>;
type UserSummary = Pick<User, "id" | "name">;
type Permissions = Record<"read" | "write", boolean>;
function createUser(): User {
return { id: 1, name: "Ada", active: true };
}
type CreatedUser = ReturnType<typeof createUser>;Conditional Types
A conditional type chooses a type based on a condition:
type ElementType<T> = T extends (infer U)[] ? U : T;This reads as: if T is an array, return its element type; otherwise, return T.
The infer keyword declares a temporary type variable inside a matching pattern. Here, U captures the array element type.
Distributive Conditional Types
When a conditional type checks a naked type parameter, it distributes over unions:
type ToArray<T> = T extends unknown ? T[] : never;
type Result = ToArray<string | number>; // string[] | number[]To process the union as one value, wrap the parameter in tuples:
type WholeArray<T> = [T] extends [unknown] ? T[] : never;
type Combined = WholeArray<string | number>; // (string | number)[]Common Pitfalls and Good Practice
- Use a generic only when it relates multiple types. A parameter used once may be clearer as
unknown. - Add constraints when the implementation needs specific properties.
- Prefer built-in utilities over repeating mapped types.
- Check whether a conditional type should distribute over a union.
> callout tip > Generics describe relationships. They should preserve useful information, not merely make a declaration look more advanced.
Variance in Generic Types
Variance describes how type compatibility changes when a type parameter changes. Mutable containers can be unsafe when a broader type is substituted for a narrower one. Read-only data is usually safer because it cannot receive an incompatible value. Treat generic function parameters carefully, especially when callbacks accept values.
Exercise
What is the result of ToArray<boolean | Date>?
Show answer
boolean[] | Date[], because the conditional type distributes over the union.