Utility types
Overview
Real applications need many variations of the same type: a User from the database, the input for creating a user (no id yet), an update where every field is optional, a public version without the email. Writing each by hand duplicates the model. TypeScript ships with utility types that build these variations for you.
All of these are generic types defined in TypeScript’s standard library — and in the next lessons you’ll learn to write them yourself.
Changing modifiers: Partial, Required, Readonly
type User = { id: number; name: string; email: string; bio?: string };
type UserDraft = Partial<User>; // every property optional
type FullUser = Required<User>; // bio is now required too
type FrozenUser = Readonly<User>; // every property readonlyPartial is the classic type for updates:
function updateUser(user: User, changes: Partial<User>): User {
return { ...user, ...changes };
}
updateUser(user, { name: "Asha R." }); // ✓ any subsetReadonly is shallow: nested objects and arrays inside can still be changed.
Selecting properties: Pick and Omit
type UserPreview = Pick<User, "id" | "name">; // { id: number; name: string }
type NewUser = Omit<User, "id">; // { name; email; bio? }Combine them for precise variants:
// Only these fields may be updated, and each is optional
type UserUpdate = Partial<Pick<User, "name" | "email" | "bio">>;Pick checks its keys (Pick<User, "phone"> is an error); Omit accepts any string, so a typo in Omit silently removes nothing. Double-check Omit keys.
Building object types: Record
Record<K, V> — covered in Index signatures and records — creates an object type with keys K and values V:
type Permissions = Record<User["role"], string[]>;Filtering unions: Exclude, Extract, NonNullable
These work on unions, removing or keeping members:
type Role = "admin" | "editor" | "guest";
type StaffRole = Exclude<Role, "guest">; // "admin" | "editor"
type Elevated = Extract<Role, "admin" | "owner">; // "admin"
type MaybeName = string | null | undefined;
type Name = NonNullable<MaybeName>; // stringExclude and Extract also filter by shape: Extract<Shape, { kind: "circle" }> picks the circle member out of a discriminated union.
Types from functions: ReturnType, Parameters, Awaited
function createSession(userId: number, remember = false) {
return { token: crypto.randomUUID(), userId, expires: new Date() };
}
type Session = ReturnType<typeof createSession>;
type SessionArgs = Parameters<typeof createSession>; // [userId: number, remember?: boolean]For async functions, ReturnType gives a Promise<…>; Awaited unwraps it:
async function fetchUser(id: number) { … return user; }
type Pending = ReturnType<typeof fetchUser>; // Promise<User>
type Loaded = Awaited<ReturnType<typeof fetchUser>>; // UserThese are invaluable when a library exports a function but not the types of its arguments or results.
More you’ll meet
| Utility | Does |
|---|---|
ConstructorParameters<typeof C> |
a class constructor’s parameters |
InstanceType<typeof C> |
the instance type of a class |
NoInfer<T> |
stops TypeScript inferring a type parameter from this position |
Uppercase<S>, Lowercase<S>, Capitalize<S> |
change the case of string literal types (Template literal types) |
Composing utilities
Utility types nest. Read them inside-out:
type EditableProfile = Readonly<Pick<User, "id">> & Partial<Omit<User, "id">>;
// id is readonly and required; everything else optionalIf a composition gets hard to read, give each step a name:
type UserKey = Pick<User, "id">;
type UserFields = Omit<User, "id">;
type EditableProfile = Readonly<UserKey> & Partial<UserFields>;A typical set of model types
type Product = { id: string; name: string; price: number; createdAt: Date };
type NewProduct = Omit<Product, "id" | "createdAt">; // POST body
type ProductUpdate = Partial<NewProduct>; // PATCH body
type ProductSummary = Pick<Product, "id" | "name">; // list viewOne model, every variant derived — add a field to Product and the create, update and summary types all follow. You’ll use exactly this pattern in the final project.
Remember: write the main type once, then derive variations with
Partial,Pick,Omit,Readonly,Excludeand friends. If you’re copying properties between types, there’s probably a utility for it.
Types for a user service
From the single User type, derive (don’t rewrite!): NewUser — everything except id and createdAt (Omit); UserUpdate — any subset of name, email and role (Partial + Pick); PublicUser — only id, name and role (Pick); FrozenUser (Readonly); StaffRole — the roles except "guest" (Exclude). Write createUser(input: NewUser, id: number): User, updateUser(user: User, changes: UserUpdate): User, toPublic(user: User): PublicUser and isStaff(role: User["role"]): role is StaffRole. Use them and print the results. Also derive type Loaded = Awaited<ReturnType<typeof loadUser>> for the given async function. Show with // @ts-expect-error that an update can’t change id and a FrozenUser can’t be modified.
type User = {
id: number;
name: string;
email: string;
role: "admin" | "editor" | "guest";
createdAt: Date;
};
async function loadUser(id: number) {
return { id, name: "Loaded", email: "l@example.com", role: "guest" as const, createdAt: new Date(0) };
}
// Derived types
// Functionstype User = {
id: number;
name: string;
email: string;
role: "admin" | "editor" | "guest";
createdAt: Date;
};
async function loadUser(id: number) {
return { id, name: "Loaded", email: "l@example.com", role: "guest" as const, createdAt: new Date(0) };
}
// Derived types
type NewUser = Omit<User, "id" | "createdAt">;
type UserUpdate = Partial<Pick<User, "name" | "email" | "role">>;
type PublicUser = Pick<User, "id" | "name" | "role">;
type FrozenUser = Readonly<User>;
type StaffRole = Exclude<User["role"], "guest">; // "admin" | "editor"
type Loaded = Awaited<ReturnType<typeof loadUser>>;
// Functions
function createUser(input: NewUser, id: number): User {
return { ...input, id, createdAt: new Date("2026-12-04") };
}
function updateUser(user: User, changes: UserUpdate): User {
return { ...user, ...changes };
}
function toPublic({ id, name, role }: User): PublicUser {
return { id, name, role };
}
function isStaff(role: User["role"]): role is StaffRole {
return role !== "guest";
}
const asha = createUser({ name: "Asha", email: "asha@example.com", role: "editor" }, 1);
const promoted = updateUser(asha, { role: "admin" });
console.log(toPublic(promoted)); // { id: 1, name: 'Asha', role: 'admin' }
console.log(isStaff(promoted.role), isStaff("guest")); // true false
const loaded: Loaded = await loadUser(7);
console.log(loaded.name, loaded.role); // Loaded guest
// @ts-expect-error -- id is not part of UserUpdate
updateUser(asha, { id: 99 });
const frozen: FrozenUser = asha;
// @ts-expect-error -- every property is readonly
frozen.name = "Changed";Summary
- Utility types transform existing types:
Partial,RequiredandReadonlychange every property’s modifiers. Pick<T, Keys>keeps some properties,Omit<T, Keys>removes some — perfect for create/update/public variants.Exclude,ExtractandNonNullablefilter union members.ReturnType,ParametersandAwaitedderive types from functions and promises.- Derived types stay in sync: change the base type and every variant updates.