TypeScript Pick and Omit in Use
Pick builds a smaller type by keeping named members of a base type. Omit builds a smaller type by dropping named members.
A public view with Pick
The base model carries server fields. The public view keeps only the members a reader may see.
interface Article {
id: number;
title: string;
body: string;
authorId: number;
createdAt: string;
}
type PublicArticle = Pick<Article, "id" | "title" | "body">;
const pub: PublicArticle = { id: 5, title: "Guide", body: "Text" };
console.log(pub.id);
console.log(pub.title);
console.log(pub.body);An input form type with Omit
The form type drops the server-owned fields id, authorId and createdAt. The editor supplies only title and body.
interface Article {
id: number;
title: string;
body: string;
authorId: number;
createdAt: string;
}
type ArticleInput = Omit<Article, "id" | "authorId" | "createdAt">;
const formInput: ArticleInput = { title: "Draft", body: "Words" };
console.log(formInput.title);
console.log(formInput.body);Pick refuses an unknown key
The base type has no summary member. Pick rejects the name at compile time.
interface Article {
id: number;
title: string;
body: string;
authorId: number;
createdAt: string;
}
type BadView = Pick<Article, "title" | "summary">;Example
interface ProductItem {
id: number;
sku: string;
displayName: string;
price: number;
costPrice: number;
}
type PublicProduct = Pick<ProductItem, "displayName" | "price">;
type ProductInput = Omit<ProductItem, "id" | "sku">;
const pub: PublicProduct = { displayName: "Pen", price: 250 };
const input: ProductInput = {
displayName: "Pen",
price: 250,
costPrice: 140,
};
console.log(pub.displayName);
console.log(pub.price);
console.log(input.costPrice);Key points
- Pick<T, K> keeps only the listed keys of T.
- Omit<T, K> keeps every key of T except the listed ones.
- Pick refuses a key that does not exist on the base type.
- A view type is derived from the base type, so it stays in step with it.
In this example, Pick exposes a small public view of ProductItem, while Omit builds the wider internal input type from the same base model.
Note
Pick and Omit work on keys, so both need a base object type.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท TypeScript Playground
Exercise
What happens when Pick names a key that the base type does not have?