TypeScript utility types let you derive dependable DTOs, form models, configuration objects, and API contracts without repeating every property by hand. This cookbook explains which built-in utility to choose, shows copy-ready patterns for common transformations, and highlights where a convenient type can accidentally weaken your application’s guarantees.
Overview
A utility type transforms an existing type into another type. Instead of declaring a second interface for every variation of a model, you can express the relationship directly:
interface User {
id: string;
name: string;
email: string;
role: "admin" | "member";
createdAt: Date;
}
type UserPreview = Pick<User, "id" | "name">;
type UserPatch = Partial<Omit<User, "id" | "createdAt">>;
Here, Pick selects fields and Omit removes fields. Wrapping the result in Partial makes the remaining properties optional, which is useful for a patch request. The resulting type stays connected to User; if a selected property changes, the compiler can expose affected code.
The most useful TypeScript utility types are not interchangeable. A reliable choice depends on whether you are selecting properties, changing optionality, restricting mutability, deriving a function’s shape, or mapping one set of keys to another.
Utility types cheat sheet
| Task | Use | Typical example |
|---|---|---|
| Make all properties optional | Partial<T> | Update or draft models |
| Make all properties required | Required<T> | Validated configuration |
| Select known properties | Pick<T, K> | Public response DTO |
| Remove known properties | Omit<T, K> | Create or update payload |
| Map keys to one value type | Record<K, V> | Event handlers or feature flags |
| Prevent property reassignment | Readonly<T> | Immutable input or snapshot |
| Unwrap a promise-like result | Awaited<T> | Async service return type |
| Get a function’s return type | ReturnType<F> | Adapter or test type |
| Get a function’s parameters | Parameters<F> | Wrapper or forwarding function |
For a broader project-level checklist, pair these patterns with a strict compiler configuration. The TypeScript strict mode rollout guide is useful when a codebase is adopting stronger checking incrementally.
Template structure
A maintainable derived type usually follows four steps:
- Start with a source model. Define the domain, persistence, or API type that owns the relevant fields.
- Choose the transformation that matches the boundary. Select fields for a response, remove server-owned fields from input, or make only update fields optional.
- Add explicit exceptions. If one property needs a different rule, intersect the derived type with an override rather than weakening the entire model.
- Check the runtime boundary separately. Utility types disappear at runtime. Incoming JSON still needs parsing, validation, or another runtime safety mechanism.
For example, a create request normally should not accept an identifier or server-managed timestamp:
interface Product {
id: string;
name: string;
priceInCents: number;
inventory: number;
createdAt: string;
}
type CreateProductInput = Omit<Product, "id" | "createdAt">;
type ProductResponse = Pick<Product, "id" | "name" | "priceInCents">;
This is clearer than copying the same three or four fields into separate interfaces. It also communicates ownership: the client supplies product details, while the server supplies the identifier and creation time.
Use the smallest transformation that tells the truth
Prefer Pick when you are defining a narrow public view. Prefer Omit when the model’s remaining fields are genuinely part of the boundary and only a small server-owned set must be excluded. If the boundary has different names, nesting, or validation rules, create a dedicated type instead of forcing a utility type to represent a different concept.
For example, an API response that changes createdAt from a string to a Date is not accurately modeled by Pick<Product, ...> alone. A dedicated mapped or intersection type may be better, but the runtime conversion must also happen in code.
How to customize
Partial for patch requests, not general input
Partial<T> makes every property optional, including properties that may be essential when present. It is a good fit for a patch operation where an omitted field means “leave unchanged.” It is usually too broad for a create request or a form that has required fields.
type UpdateProfileInput = Partial<Pick<User, "name" | "email">> & {
// If needed, add an operation-specific property:
notifyByEmail?: boolean;
};
When a patch must contain at least one field, the type system may need a more specific union or runtime check. Partial<T> by itself also permits an empty object.
Required for finalized configuration
Configuration often begins as partial input and becomes complete after defaults are applied:
interface AppConfig {
apiUrl?: string;
timeoutMs?: number;
logLevel?: "debug" | "info" | "warn" | "error";
}
type ResolvedConfig = Required<AppConfig>;
function resolveConfig(input: AppConfig): ResolvedConfig {
return {
apiUrl: input.apiUrl ?? "https://example.test",
timeoutMs: input.timeoutMs ?? 5000,
logLevel: input.logLevel ?? "info",
};
}
Only return ResolvedConfig after the implementation has actually filled every field. Required does not apply defaults and cannot prove that a runtime object is complete.
Record for closed sets of keys
Record<K, V> is helpful when every member of a known key union must have a value:
type Status = "pending" | "active" | "archived";
type StatusLabels = Record<Status, string>;
const statusLabels: StatusLabels = {
pending: "Pending",
active: "Active",
archived: "Archived",
};
If a key is genuinely optional, use Partial<Record<K, V>>. Do not use a broad string index when the application supports only a fixed set of keys; the union gives the compiler a chance to detect missing cases and spelling errors.
Readonly for ownership boundaries
Readonly<T> prevents reassignment through that type, which is useful for function inputs, snapshots, and shared state views:
function renderSummary(user: Readonly<User>): string {
return `${user.name} (${user.role})`;
}
It is shallow. Nested objects and arrays may still be mutable unless you define a deep-readonly utility or use an immutable data design. A type-level readonly promise should match the actual ownership rules of the application.
Derive function wrappers with ReturnType and Parameters
Function utilities are useful when a wrapper should stay synchronized with an implementation:
async function loadUser(id: string) {
return { id, name: "Ada" };
}
type LoadUserResult = Awaited<ReturnType<typeof loadUser>>;
type LoadUserArguments = Parameters<typeof loadUser>;
async function loggedLoadUser(...args: LoadUserArguments): Promise<LoadUserResult> {
console.log("Loading user", args[0]);
return loadUser(...args);
}
ReturnType produces the function’s return type, while Awaited unwraps the promise. This avoids manually repeating the result shape in adapters, mocks, and instrumentation. Keep in mind that overloaded functions and generic functions can produce less specific derived types than expected; inspect the inferred result before building a public contract around it.
Examples
Form state with a deliberate distinction
A form often needs values, validation errors, and submission state. Do not make the domain model itself optional just because the form starts incomplete:
type Account = {
displayName: string;
email: string;
marketingOptIn: boolean;
};
type AccountFormValues = Partial<Account>;
type AccountFormErrors = Partial<Record<keyof Account, string>>;
type AccountFormState = {
values: AccountFormValues;
errors: AccountFormErrors;
isSubmitting: boolean;
};
Before sending the form, validate and convert values into a complete Account. This separates an incomplete UI state from a valid domain object.
Event maps with mapped types
Mapped types can derive an event handler map from a payload map:
type EventPayloads = {
userCreated: { id: string };
invoicePaid: { invoiceId: string; amount: number };
sessionExpired: undefined;
};
type EventHandlers = {
[EventName in keyof EventPayloads]:
(payload: EventPayloads[EventName]) => void;
};
Each handler receives the payload associated with its key. This is more precise than using one broad callback type. If the event list is shared across packages, consider how the type is exported and versioned; declaration-file and package-boundary concerns are covered in the declaration files guide.
Conditional utilities for nullable values
Conditional types can encode a reusable rule. This example removes null and undefined from a type before creating a result:
type Present<T> = T extends null | undefined ? never : T;
type ApiValue = string | null | undefined;
type RequiredApiValue = Present<ApiValue>; // string
Conditional types distribute over unions in many cases, which is why the example removes each nullable member. Use this power sparingly: a named, simple domain type is often easier to understand than a deeply nested conditional expression.
Common failure modes
- Using
Partialeverywhere: this can make required business data appear optional throughout the application. - Assuming
Omitrenames fields: it only removes keys. Use a new type when the API uses a different name. - Confusing readonly with deep immutability: nested values may remain changeable.
- Trusting types at runtime: JSON, query parameters, and environment variables still need runtime validation or parsing.
- Over-deriving external contracts: internal models can change for reasons unrelated to a stable public API. A dedicated DTO may be safer at a long-lived boundary.
When to update
Revisit this utility types reference whenever you introduce a new endpoint, form, configuration layer, event map, or function wrapper. Start by asking what the boundary means: is a missing value different from an explicit undefined? Does omission mean “unchanged,” or is the field required? Which properties are client-owned, and which are generated by the server?
Also review derived types when the source model changes. A new required property may make a Pick-based response incomplete, while a renamed field can make an Omit-based input silently describe the wrong boundary after a refactor. Run the compiler and type-level tests as part of the change rather than relying on visual inspection.
Finally, check the TypeScript version and compiler configuration when inference behavior or built-in utilities evolve. Keep examples compatible with the project’s supported version, and avoid presenting a clever custom mapped type as a universal replacement for a straightforward interface. For practical follow-up, use the TypeScript testing patterns guide to add compile-time assertions around important transformations, then document any intentional exceptions near the type definition.
The best utility type is the one that preserves the real constraint of the boundary with the least indirection. Choose the narrowest built-in transformation that fits, customize only where the model demands it, and validate every value that crosses from untyped runtime data into your typed application.