Pick, Omit
type Pick<T, K extends keyof T> = {
[P in K]: T[P];
};
type Omit<T, K extends keyof any> = Pick<T, Exclude<keyof T, K>>;Keep or remove properties from an object type by key. Pick rejects keys that are not on T; Omit does not.
| Type parameter | Description |
|---|---|
T | The source object type. |
K | For Pick, a union of keys that must already exist on T. For Omit, a union of keys to remove; keys that are not on T are ignored. |
Produces: A new object type with the selected or remaining properties. No runtime object is created.
Type errors
type error— Pick<T, K> is an error when K is not assignable to keyof T. Accessing a property that was omitted, or a property that was never picked, is also an error.
- Omit arrived in TypeScript 3.5. The declaration above is from TypeScript 5.9.3.
- Use Pick when you want the compiler to tell you that a key does not exist. Use Omit when you want to subtract keys, and double-check the spelling.
type User = { name: string; age?: number; city: string };
type NameAndAge = Pick<User, "name" | "age">;
const picked: NameAndAge = { name: "Ada", age: 36 };
// @ts-expect-error Pick does not include city
picked.city = "Paris";
// @ts-expect-error every key passed to Pick must exist on the source type
type BadPick = Pick<User, "country">;
type WithoutCity = Omit<User, "city">;
const omitted: WithoutCity = { name: "Ada" };
// @ts-expect-error city was omitted
omitted.city = "Paris";
type StillHasCity = Omit<User, "country">;
const kept: StillHasCity = { name: "Ada", city: "Paris" };
console.log(picked.name, omitted.name, kept.city);Expected output
Ada Ada ParisRelated: Official Pick, Official Omit