7. Utility types
TypeScript · 44 pages source format
Built-in type transformers: Partial, Required, Pick, Omit, Record, Readonly, ReturnType, Parameters. Compose them for DRY API types. keyof and indexed access types unlock advanced patterns.
What you'll learn
- Partial & Required
- Pick & Omit
- Record & Readonly
- ReturnType & Parameters
- keyof patterns
Partial and Required
Partial<User> makes all fields optional — update DTOs. Required<User> opposite — after validation.
Do this now
Create UpdateUserInput = Partial<Pick<User, "name" | "email">>.
Pick and Omit
Pick<User, "id" | "name"> for list views. Omit<User, "password"> for public API.
type PublicUser = Omit<User, "password">
type UserSummary = Pick<User, "id" | "name">Do this now
Define PublicUser = Omit<User, "email"> and UserSummary = Pick<User, "id" | "name">.
Record and Readonly
Record<string, number> for dictionaries. Readonly<User> prevents mutation at type level.
Do this now
Type a scores map: Record<string, number>. Function accept Readonly<User>.
ReturnType and Parameters
Extract function return: ReturnType<typeof getPost>. Extract args: Parameters<typeof getPost>[0].
Do this now
type Post = Awaited<ReturnType<typeof getPost>>. Use instead of duplicating interface.
Compose utilities
Real patterns combine: Partial<Pick<...>>, Readonly<Record<...>>. Do not hand-write what utilities provide.
Do this now
Refactor 2 duplicated types to use Pick/Omit/Partial composition.