Mapped and conditional types
Utility types like Partial and Pick aren't magic. They're written in TypeScript itself using mapped and conditional types. Learning these lets you build your own type tools, and read the type definitions of any library.
keyof and indexed access (recap)
typeof: get a type from a value
Mapped types: transform every property
A mapped type loops over keys with [K in Keys]:
The as clause renames keys, using template literal types.
Conditional types: T extends U ? X : Y
A type-level if:
infer: extract part of a type
infer declares a type variable that captures part of the matched type. This is how ReturnType and Awaited are built:
Distributive conditional types
When T is a union, conditional types apply to each member separately:
Putting it together: a type-safe event emitter
Libraries like tRPC, Zod, Prisma and React Hook Form use exactly these techniques to give you end-to-end type safety.
Keep it readable. Advanced types are powerful, but your teammates must understand them. Prefer simple types in application code, and save the clever ones for shared libraries.
Practice
- Write
Nullable<T>, which makes every property of T acceptnulltoo. - Write
FunctionKeys<T>, the keys of T whose values are functions. (Hint: a mapped type withasplus a conditional type; key remapping toneverremoves a key.)
1.What does { [K in keyof T]?: T[K] } produce?
2.In T extends Promise<infer V> ? V : T, what does infer V do?