Practical guide to Partial, Required, Pick, Omit, Record, Extract, Exclude, ReturnType, Parameters, and Awaited with real-world examples.
Practical guide to Partial, Required, Pick, Omit, Record, Extract, Exclude, ReturnType, Parameters, and Awaited with real-world examples.
BeforeMerge offers hundreds of code review rules, guides, and detection patterns to help your team ship better code.
Built-in utility types transform existing types without rewriting them. These are essential for DRY type definitions.
Makes all properties optional.
interface User { name: string; email: string; age: number; }
type UpdateUser = Partial<User>;
// { name?: string; email?: string; age?: number; }
function updateUser(id: string, changes: Partial<User>) {
return db.update(id, changes);
}Makes all properties required (opposite of Partial).
interface Config { host?: string; port?: number; }
type StrictConfig = Required<Config>;
// { host: string; port: number; }Extracts a subset of properties.
type UserPreview = Pick<User, "name" | "email">;
// { name: string; email: string; }Removes specified properties.
type CreateUser = Omit<User, "id" | "createdAt">;
// Everything except id and createdAtCreates an object type with keys of type K and values of type V.
type StatusMap = Record<"active" | "inactive" | "pending", User[]>;
// { active: User[]; inactive: User[]; pending: User[]; }
// Dynamic lookup tables
const cache: Record<string, unknown> = {};Extracts members from a union that are assignable to U.
type Events = "click" | "scroll" | "mousemove" | "keydown";
type MouseEvents = Extract<Events, "click" | "mousemove" | "scroll">;
// "click" | "mousemove" | "scroll"Removes members from a union.
type NonMouseEvents = Exclude<Events, "click" | "mousemove" | "scroll">;
// "keydown"
// Common: remove null/undefined
type NonNullableString = Exclude<string | null | undefined, null | undefined>;
// stringExtracts the return type of a function.
function createUser() {
return { id: "1", name: "Alice", role: "admin" as const };
}
type CreatedUser = ReturnType<typeof createUser>;
// { id: string; name: string; role: "admin"; }Extracts parameter types as a tuple.
function search(query: string, limit: number, offset: number) { /* ... */ }
type SearchParams = Parameters<typeof search>;
// [query: string, limit: number, offset: number]Unwraps the resolved type of a Promise.
async function fetchUser() { return { id: "1", name: "Alice" }; }
type User = Awaited<ReturnType<typeof fetchUser>>;
// { id: string; name: string; }// API response: pick fields and make them all optional except id
type PatchPayload = Partial<Omit<User, "id">> & Pick<User, "id">;
// Form state: all fields optional, plus dirty tracking
type FormState<T> = {
values: Partial<T>;
dirty: Partial<Record<keyof T, boolean>>;
};