TypeScript · Lesson 27 of 42
Built-in utility types: Partial, Pick, Omit and more
Reshape existing types with Partial, Required, Readonly, Pick, Omit, Record, Exclude, Extract, NonNullable, ReturnType and Parameters.
UNDERSTAND IT. THEN TRY IT.
What you can do after this lesson
You will stop copying and editing types by hand. TypeScript ships with a set of generic helper types that reshape other types. Learning a handful of them saves a great deal of repetition, and keeps related types automatically in step with each other.
The starting type
All the examples use this type:
type User = {
id: number;
name: string;
email: string;
age?: number;
};Partial and Required
Partial<T> makes every property optional. It is perfect for update functions, where the caller supplies only the fields that change:
type User = { id: number; name: string; email: string };
function updateUser(user: User, changes: Partial<User>): User {
return { ...user, ...changes };
}
const user: User = { id: 1, name: "Asha", email: "asha@example.com" };
console.log(updateUser(user, { name: "Asha K." }));
console.log(updateUser(user, { email: "new@example.com" }));{ id: 1, name: 'Asha K.', email: 'asha@example.com' }
{ id: 1, name: 'Asha', email: 'new@example.com' }Required<T> is the opposite: it makes every optional property required. Use it after you have filled in defaults.
type Settings = { theme?: string; fontSize?: number };
const complete: Required<Settings> = { theme: "dark" };example.ts(3,7): error TS2741: Property 'fontSize' is missing in type '{ theme: string; }' but required in type 'Required<Settings>'.Readonly
Readonly<T> makes every property read-only, so assignments are errors:
type Point = { x: number; y: number };
const origin: Readonly<Point> = { x: 0, y: 0 };
origin.x = 5;example.ts(4,8): error TS2540: Cannot assign to 'x' because it is a read-only property.Pick and Omit
Pick<T, Keys> builds a type with only the keys you list. Omit<T, Keys> builds one with everything except the listed keys. Public views and creation inputs are typical uses:
type User = { id: number; name: string; email: string; password: string };
type PublicUser = Pick<User, "id" | "name">;
type NewUser = Omit<User, "id">;
const visible: PublicUser = { id: 1, name: "Asha" };
const input: NewUser = { name: "Ben", email: "ben@example.com", password: "secret" };
console.log(visible, Object.keys(input));{ id: 1, name: 'Asha' } [ 'name', 'email', 'password' ]Because these are derived from User, adding a field to User flows through automatically. Omit<User, "password"> is a common way to describe a type that should not include the password. Remember that it only changes the type: types are erased, so the object you actually send still contains password unless your code builds a new object without it.
Record
Record<Keys, Value> builds an object type whose keys are Keys and whose values are all Value. With a union of literals as keys, it forces you to provide every key:
type Role = "admin" | "editor" | "viewer";
const permissions: Record<Role, string[]> = {
admin: ["read", "write", "delete"],
editor: ["read", "write"],
viewer: ["read"],
};
console.log(permissions.editor);[ 'read', 'write' ]Leave a role out, and the compiler tells you which one:
type Role = "admin" | "editor" | "viewer";
const permissions: Record<Role, string[]> = {
admin: ["read", "write", "delete"],
editor: ["read", "write"],
};example.ts(3,7): error TS2741: Property 'viewer' is missing in type '{ admin: string[]; editor: string[]; }' but required in type 'Record<Role, string[]>'.Record<string, number> is the compact form of the index signature from the object types lesson.
Exclude, Extract and NonNullable
These three filter unions. Exclude<T, U> removes members assignable to U, Extract<T, U> keeps only those members, and NonNullable<T> removes null and undefined:
type Event = "click" | "scroll" | "keydown" | "keyup";
type KeyEvent = Extract<Event, "keydown" | "keyup">;
type NonKeyEvent = Exclude<Event, "keydown" | "keyup">;
type Present = NonNullable<string | null | undefined>;
const a: KeyEvent = "keyup";
const b: NonKeyEvent = "click";
const c: Present = "text";
console.log(a, b, c);keyup click textReturnType and Parameters
Two utilities read a function type. ReturnType<F> gives what it returns and Parameters<F> gives a tuple of its parameter types. Use them with typeof to avoid repeating a type that already exists in code:
function createUser(name: string, age: number) {
return { id: Math.floor(Math.random() * 1000), name, age, active: true };
}
type NewUserResult = ReturnType<typeof createUser>;
type CreateUserArgs = Parameters<typeof createUser>;
const args: CreateUserArgs = ["Asha", 30];
const user: NewUserResult = createUser(...args);
console.log(user.name, user.age, user.active);Asha 30 trueIf createUser changes, both derived types follow without any edit.
Combining utilities
Utilities nest, because each one produces a type. A common recipe is an update type that cannot change the id:
type User = { id: number; name: string; email: string };
type UserUpdate = Partial<Omit<User, "id">>;
function update(changes: UserUpdate): UserUpdate {
return changes;
}
console.log(update({ name: "Asha" }));{ name: 'Asha' }A short guide
| Goal | Utility |
|---|---|
| All properties optional | Partial<T> |
| All properties required | Required<T> |
| No reassignment | Readonly<T> |
| Keep some keys | Pick<T, K> |
| Drop some keys | Omit<T, K> |
| Object from keys and value type | Record<K, V> |
| Remove union members | Exclude<T, U> |
| Keep union members | Extract<T, U> |
| Remove null and undefined | NonNullable<T> |
| What a function returns | ReturnType<F> |
| A function's parameters | Parameters<F> |
Common mistakes
Copying a type and editing it. The copy drifts out of date. Derive with Pick, Omit or Partial.
Expecting Readonly to freeze objects at run time. It only blocks assignments the compiler can see, and only at the top level.
Using Omit with a key that does not exist. Omit does not complain about a key the type does not have, so a misspelt key silently removes nothing. Check spelling carefully, or use Pick for the keys you want.
Forgetting typeof with ReturnType. ReturnType expects a function type, so give it typeof myFunction, not myFunction.
Exercise
Starting from a Product type with id, name, price and description, derive ProductSummary with Pick, NewProduct with Omit, ProductPatch with Partial, and ProductMap with Record<number, Product>. Then write a function makeProduct and derive its argument and result types with Parameters and ReturnType.
KNOWLEDGE CHECK
A quick check. You’ve got this.
Try each question. Every answer comes with an explanation.
Ready for the next small win?
Mark the lesson complete when you are ready.