Sub topic 3
Pick and Omit: selecting and removing properties
This chapter assumes you know TypeScript interfaces and type aliases, union and string literal types, and generic syntax such as Array<T>. It uses keyof and Exclude only lightly. Later chapters cover both in detail.
The problem they solve
A single domain type, such as User, usually shows up in several shapes. The database row has every field. The sign-up form has no id. The list view needs only id and name. The API response must leave out the password hash.
You could write each shape by hand, but then every change to User needs matching edits in four places. If you forget one, the copies drift apart and the compiler cannot tell you. Pick and Omit derive the smaller shapes from the original, so they stay in sync.
Pick<T, K>builds a type containing only the keysKfromT.Omit<T, K>builds a type containing every key ofTexceptK.
Both take a string literal, or a union of string literals, as the key argument.
Pick: keep only what you name
interface User {
id: number;
name: string;
email: string;
passwordHash: string;
}
type UserPreview = Pick<User, "id" | "name">;
// { id: number; name: string }
const preview: UserPreview = { id: 1, name: "Ada" };Pick checks its keys. The declaration is Pick<T, K extends keyof T>, so every name in K must be a real key of T. A typo is a compile error:
interface User {
id: number;
name: string;
}
// Error: Type '"nmae"' does not satisfy the constraint 'keyof User'.
type Broken = Pick<User, "nmae">;Because of this check, Pick is the safer choice when the result should stay small. A new field added to User never leaks into UserPreview by accident.
Omit: remove what you name
interface User {
id: number;
name: string;
email: string;
passwordHash: string;
}
type NewUser = Omit<User, "id">;
// { name: string; email: string; passwordHash: string }
type PublicUser = Omit<User, "passwordHash">;
// { id: number; name: string; email: string }Omit suits the opposite goal. You want almost everything, and the exclusion list is the short part. A field added to User later flows into PublicUser automatically. Whether that is good depends on the field. A new internalNotes field would be exposed by PublicUser without any warning.
Omit does not check its keys
The constraint on Omit is looser than the one on Pick:
interface User {
id: number;
name: string;
}
// No error. The typo silently removes nothing.
type Oops = Omit<User, "nmae">;
// { id: number; name: string }Omit is declared as Omit<T, K extends keyof any>, and keyof any is string | number | symbol. Any key name is accepted, whether or not T has it. The TypeScript team kept it this way so that Omit can work with generic and union types. The cost is that a misspelled key, or a key left over after a rename, no longer removes anything and nothing warns you.
The StrictOmit helper in the warning adds the keyof T constraint back and keeps the built-in behavior. It is a one-line custom utility type, and you will meet the ideas behind it in the chapter on writing your own.
Choosing between them
Both can produce the same type, so choose by which list is shorter and by what should happen when T grows.
| Situation | Better choice | Reason |
|---|---|---|
| Keeping 2 of 10 fields | `Pick` | Short list, and new fields stay out |
| Dropping 1 of 10 fields | `Omit` | Short list, and new fields come along |
| The result is a public or security boundary | `Pick` | An allow-list fails closed, and its keys are checked |
| Mirroring a type except for generated fields | `Omit` | Matches the intent, such as "everything but `id`" |
Ask yourself what should happen when someone adds a field to the source type. If the answer is "it should not appear here unless someone decides it should", use Pick.
Common patterns
The following example uses all of these patterns together. It is complete and runs as shown.
interface User {
id: number;
name: string;
email: string;
passwordHash: string;
createdAt: Date;
}
type NewUser = Omit<User, "id" | "createdAt">;
type PublicUser = Omit<User, "passwordHash">;
type UserPreview = Pick<User, "id" | "name">;
type UserUpdate = Partial<Omit<User, "id" | "createdAt">>;
const users: User[] = [];
let nextId = 1;
function createUser(input: NewUser): User {
const user: User = { ...input, id: nextId++, createdAt: new Date() };
users.push(user);
return user;
}
function updateUser(id: number, changes: UserUpdate): User | undefined {
const user = users.find((u) => u.id === id);
if (!user) return undefined;
Object.assign(user, changes);
return user;
}
function toPublic(user: User): PublicUser {
const { passwordHash, ...rest } = user;
return rest;
}
function toPreview(user: User): UserPreview {
return { id: user.id, name: user.name };
}
const ada = createUser({
name: "Ada",
email: "[email protected]",
passwordHash: "x9f",
});
updateUser(ada.id, { email: "[email protected]" });
console.log(toPublic(ada));
console.log(toPreview(ada));Each derived type has a clear job:
NewUseris what a caller supplies. The server generatesidandcreatedAt, so callers cannot set them.UserUpdatewrapsOmitinPartial. Callers may send any subset of the editable fields, and passingidis a compile error because the key does not exist in the type.PublicUserandUserPrevieware the shapes you hand to the outside world.
Order matters when you compose. Partial<Omit<User, "id">> first removes id, then makes the rest optional. Reversing the order, Omit<Partial<User>, "id">, gives the same result here. The two orders are not always equivalent for more complex types, so write the one that reads as your intent.
How they are built
Both types are short definitions in the standard library. A mapped type loops over a set of keys and builds a new object type. Here is Pick, and then Omit defined on top of it:
type MyPick<T, K extends keyof T> = { [P in K]: T[P] };
type MyOmit<T, K extends keyof any> = MyPick<T, Exclude<keyof T, K>>;MyPick loops over only the keys in K and looks up each property type with T[P]. MyOmit computes "all keys of T except K" with Exclude, then hands that list to MyPick. This explains the loose constraint on Omit. Exclude is happy to receive a name that is not in the union, and then removes nothing.
Edge cases
Modifiers are preserved
Pick maps over the keys it was given, and TypeScript copies the ? and readonly modifiers from the source properties. Omit inherits this because it is built on Pick.
interface Config {
readonly id: string;
label?: string;
debug: boolean;
}
type Small = Pick<Config, "id" | "label">;
// { readonly id: string; label?: string }If you want to change the modifiers as well, combine with Required, Partial or Readonly.
Index signatures defeat Omit
If a type has a string index signature, keyof of it is string | number, not a list of the literal keys. Removing a named key then removes nothing useful:
type Bag = { [key: string]: number; known: number };
type Result = Omit<Bag, "known">;
// { [x: string]: number; [x: number]: number }The result is an index-signature type, so the specific known property is gone as a named member. The surrounding index signature still accepts it. Do not rely on Omit to forbid a key on such a type.
Unions are not distributed
Pick and Omit treat a union as one object type and use only the keys common to all members. Omit<Shape, "kind"> on a union of shapes collapses to an empty object type. The fix is a distributive wrapper. The pitfalls chapter at the end of this tutorial covers it.
Classes expose only public members
keyof on a class instance type lists public members only. Pick<MyClass, "x"> cannot select a private or protected field, and the compiler reports it as an invalid key.
Types, not values
Pick and Omit work at compile time only. toPublic in the example removes passwordHash at runtime with object destructuring, and the types merely describe the result. If you return a User value typed as PublicUser, the password hash is still on the object. TypeScript allows this assignment because extra properties are fine when the value is not a fresh object literal. Always strip the data in code, not just in types.
Exercise
Given interface Account { id: string; owner: string; balance: number; internalFlag: boolean }, write a type AccountView that exposes only id and owner, using Pick. Then explain why Omit<Account, "internalFlg"> (note the typo) gives no compile error, and name one way to make the compiler catch it.
Show answer
type AccountView = Pick<Account, "id" | "owner">;. Omit is declared as Omit<T, K extends keyof any>, so any string is an accepted key. A name that does not exist in Account removes nothing, and the result still has internalFlag. To catch the typo, use Pick with an allow-list, or define type StrictOmit<T, K extends keyof T> = Omit<T, K>, which restores the keyof T check on the key argument.