Intermediate · 14 of 16 · 14 min read
Utility types
The built-in type transformations worth knowing by heart, why every one of them is shallow, and the whitelist-versus-blacklist choice between Pick and Omit.
- Utility types
The utility types are transformations the standard library ships so you do not write the same
mapped type in every project. They are the everyday face of keyof, mapped types and conditional
types — and every one of the object-shaped ones is shallow.
The object transformations
interface User {
id: number;
name: string;
email?: string;
}
type A = Partial<User>; // every property optional
type B = Required<User>; // every property required, including email
type C = Readonly<User>; // every property readonly
const a: A = {};
const b: B = { id: 1, name: "Ana", email: "a@b.c" };
const c: C = { id: 1, name: "Ana" };
// c.id = 2; // Cannot assign to 'id'
console.log(a, b.email, c.id);
They compose, and the round trip is not the identity — Required<Partial<User>> makes email
required even though it started optional:
interface User { id: number; email?: string }
type Both = Required<Partial<User>>; // { id: number; email: string }
const both: Both = { id: 1, email: "x" };
console.log(both.email);
Pick and Omit
Opposites, and they age differently:
interface User {
id: number;
name: string;
password: string;
}
type Safe = Pick<User, "id" | "name">; // a whitelist
type AlsoSafe = Omit<User, "password">; // a blacklist
const a: Safe = { id: 1, name: "Ana" };
const b: AlsoSafe = { id: 1, name: "Ana" };
console.log(a.id, b.name);
Add sessionToken: string to User and Omit lets it straight through to whatever the type was
protecting; Pick keeps it out until somebody adds it deliberately. For anything exposed —
an API response, a public DTO — the whitelist fails safer.
Omit has a second trap: it does not check that its keys exist, so a typo removes nothing.
interface User { id: number; password: string }
type Typo = Omit<User, "passwrod">; // no error, and nothing was removed
const leaked: Typo = { id: 1, password: "secret" };
console.log(Object.keys(leaked)); // ["id", "password"]
// A stricter version, if it matters:
type StrictOmit<T, K extends keyof T> = Omit<T, K>;
// type Caught = StrictOmit<User, "passwrod">; // now an error
The union filters
These work on unions rather than object shapes:
type Role = "admin" | "user" | "guest";
type A = Exclude<Role, "admin">; // "user" | "guest"
type B = Extract<Role, "admin" | "x">; // "admin"
type C = NonNullable<string | null>; // string
const a: A = "guest";
console.log(a);
Extract is more useful than it looks, because it keeps whole union members, which is how you
name one branch of a discriminated union without writing the shape again:
type State =
| { status: "ok"; data: string }
| { status: "fail"; error: Error };
type Ok = Extract<State, { status: "ok" }>; // the whole member
type NotOk = Exclude<State, { status: "ok" }>;
const ok: Ok = { status: "ok", data: "x" };
console.log(ok.data);
The function utilities
All three take a function type, usually obtained with typeof:
function createUser(name: string, age: number) {
return { id: 1, name, age, createdAt: new Date(0) };
}
type User = ReturnType<typeof createUser>;
type Args = Parameters<typeof createUser>; // [name: string, age: number]
const user: User = createUser("Ana", 30);
const args: Args = ["Beto", 25];
console.log(user.name, createUser(...args).age); // "Ana" 25
type Unwrapped = Awaited<ReturnType<() => Promise<string>>>; // string
Deriving the type from the implementation is the point: there is no second declaration to drift.
Awaited is recursive, matching what await actually does with a promise of a promise.
type A = Awaited<Promise<Promise<number>>>; // number
const a: A = 1;
console.log(a);
Record
type Role = "admin" | "user" | "guest";
const permissions: Record<Role, string[]> = {
admin: ["read", "write", "delete"],
user: ["read", "write"],
guest: ["read"],
};
// Adding a role to the union makes this object a compile error until handled.
const loose: Record<string, number> = {};
console.log(permissions.guest, loose.anything); // ["read"] undefined
With a known key union it is exhaustive, which is the useful case. With string it is just
an index signature, including the hole where a missing key reads as the value type rather than
undefined — noUncheckedIndexedAccess or a Map is the answer there.
The full list, roughly in order of use
| Utility | Does |
|---|---|
Partial<T> |
every property optional |
Required<T> |
every property required |
Readonly<T> |
every property readonly |
Pick<T, K> |
keep only these keys |
Omit<T, K> |
keep everything except these keys |
Record<K, V> |
an object with these keys and that value type |
Exclude<U, M> |
remove these members from a union |
Extract<U, M> |
keep only these members |
NonNullable<T> |
remove null and undefined |
ReturnType<F> |
what the function returns |
Parameters<F> |
its parameters, as a tuple |
Awaited<T> |
unwrap a promise, recursively |
InstanceType<C> |
what new C() produces |
Uppercase / Capitalize |
string literal transformations |
Shallow, and what to do about it
interface Config {
server: { host: string; port: number };
}
const patch: Partial<Config> = { server: { host: "x", port: 1 } };
// The nested object still needs BOTH properties:
// const bad: Partial<Config> = { server: { host: "x" } }; // 'port' is missing
type DeepPartial<T> = T extends object
? { [K in keyof T]?: DeepPartial<T[K]> }
: T;
const deep: DeepPartial<Config> = { server: { host: "x" } };
console.log(patch.server?.port, deep.server?.host);
The same applies to Readonly. A deep version is a recursive mapped type, and the care is in the
base case: arrays, Date, Map and functions all satisfy extends object and usually should not
be walked into.
They are all mapped types underneath
Knowing that is the difference between using them and writing the one that is missing:
type MyPartial<T> = { [K in keyof T]?: T[K] };
type MyRequired<T> = { [K in keyof T]-?: T[K] };
type MyReadonly<T> = { readonly [K in keyof T]: T[K] };
type MyPick<T, K extends keyof T> = { [P in K]: T[P] };
type MyRecord<K extends PropertyKey, V> = { [P in K]: V };
type MyExclude<T, U> = T extends U ? never : T;
type MyOmit<T, K extends PropertyKey> = MyPick<T, MyExclude<keyof T, K>>;
interface User { id: number; name: string }
type Test = MyOmit<User, "id">; // { name: string }
const t: Test = { name: "Ana" };
console.log(t.name);
Omit built from Pick and Exclude is exactly how the standard library defines it.
Common mistakes
Expecting them to be deep
Mistake. Partial<Config> for a nested patch payload.
Why it fails. Only the top level becomes optional; nested objects keep every required
property.
What to do instead. A recursive DeepPartial, with an explicit base case for arrays and
built-ins.
Omit as a security boundary
Mistake. Omit<User, "password"> as the public shape.
Why it fails. It is a blacklist: a new sensitive field added to User passes straight
through, and a typo in the key removes nothing silently.
What to do instead. Pick the fields you intend to expose.
Partial on a function’s required arguments
Mistake. function update(user: Partial<User>) where id is needed to find the record.
Why it fails. Every property is now optional, including the one that must be there.
What to do instead. Pick<User, "id"> & Partial<Omit<User, "id">>, which says what you mean.
Check yourself
4 questions from the bank on what you just read. Answering here does not affect your quiz history.
What does Partial<User> produce?
What is the difference between Pick<User, "id"> and Omit<User, "id">?
The utility types compose, and reading one is a matter of working outwards.
What does Required<Partial<User>> give you?
interface User { id: number; name?: string }What do ReturnType<T> and Parameters<T> extract?
Further reading
Everything above is meant to be enough on its own. These are for when you want the full specification of a detail.
Reaching the end of a lecture marks it as read.