Using TypeScript's helper types, you can copy selective/specific properties over to a new type from an existing type or interface. In this article, we're going to look at how this can be done.
#Choosing the Properties to Include From an Existing Type
You can specify the set of properties you wish to include in the new type by specifying the keys in Pick<Type, Keys> helper type (TypeScript 2.1+) like so:
interface Product {
name: string;
price: number;
description: string;
lastUpdated: string;
};
// ts 2.1+
type ProductPreview = Pick<Product, 'name' | 'price'>;
// usage
const product: ProductPreview = {
name: 'Blue Bag',
price: 200,
};
#Choosing the Properties to Exclude From an Existing Type
You can choose to drop some properties from the original type using:
Omit<Type, Keys>helper type (TypeScript 3.5+);- Combination of
PickandExclude<keyof Type, Keys>helper types (TypeScript 2.8+).
For example:
interface Product {
name: string;
price: number;
description: string;
lastUpdated: string;
};
// ts 3.5+
type ProductPreview = Omit<Product, 'description' | 'lastUpdated'>;
// ts 2.8+
type ProductPreview = Pick<Product, Exclude<keyof Product, 'description' | 'lastUpdated'>>;
// usage
const product: ProductPreview = {
name: 'Blue Bag',
price: 200,
};