Utility types¶
This lesson covers the built-in utility types that transform existing types without repeating yourself.
Common utilities¶
TypeScript ships with helpers that modify properties, keys, and structure.
Partial<T>¶
Makes every property optional.
Required<T>¶
Makes every property required.
Pick<T, K>¶
Keeps only the chosen properties.
Omit<T, K>¶
Removes the chosen properties.
Readonly<T>¶
Makes every property readonly.
Record<K, V>¶
Creates a type with keys K and values V.
ReturnType and Parameters¶
Extract a function's return type or parameter tuple.
function createUser(name: string, age: number): User {
return { id: '1', name, email: '', age, isAdmin: false }
}
type CreateUserReturn = ReturnType<typeof createUser>
type CreateUserParams = Parameters<typeof createUser>
keyof and indexed access¶
type UserKey = keyof User // 'id' | 'name' | 'email' | 'age' | 'isAdmin'
type UserName = User['name'] // string
typeof for values¶
Derive a type from a value.
Mapped types¶
Create a new type by transforming each property.
Tip
Utility types are most useful when the original type already describes the source of truth. They reduce duplicated shape definitions.
Hands-on: profile editor¶
- Create
src/profile.ts. - Define
interface Userwithid,name,email,age, andisAdmin. - Define
type UserUpdate = Partial<Omit<User, 'id' | 'isAdmin'>>for fields a user can edit. - Write
function applyUpdate(user: User, update: UserUpdate): Userthat returns a new user with changes merged in. - Use
Readonly<User>for acurrentUserconstant and try to mutate it. - Use
Record<string, User>to build auserByEmaillookup. - Use
ReturnTypeto define a type alias from afunction makeUser(): User.