How to Selectively Copy Properties From an Existing Type or Interface in TypeScript?

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:

  1. Omit<Type, Keys> helper type (TypeScript 3.5+);
  2. Combination of Pick and Exclude<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,
};

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.