How to exclude properties from interface while inheriting

Typescript >3.5

TypeScript 3.5 introduced the Omit helper type, which creates a new type with some properties dropped from the original. The example from the docs:

type Person = {
    name: string;
    age: number;
    location: string;
};

type QuantumPerson = Omit<Person, "location">;

// equivalent to
type QuantumPerson = {
    name: string;
    age: number;
};

Thanks to Jeremy for the update on Typescript 3.5!

Typescript >2.8

This can be implemented using the Pick and Exclude types introduced in Typescript 2.1 and 2.8:

/**
 * From T pick a set of properties K
 */
type Pick<T, K extends keyof T> = {
    [P in K]: T[P];
};

/**
 * Exclude from T those types that are assignable to U
 */
type Exclude<T, U> = T extends U ? never : T;

With these type definitions you can construct Omit<T,K> to omit specific properties from a generic type:

/**
 * From T pick all properties except the set of properties K
 */
export type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>;

To state the Typescript 2.8 Release Notes why this type is not included in Typescript:

We did not include the Omit type because it is trivially written as Pick<T, Exclude<keyof T, K>>.

Although it is not included in Typescript several libraries provide their own similar Omit type, including react-redux or Material-UI.

Here is a working example:

interface X {
  x1: string;
  x2: string;
}

type Y = Omit<X, 'x2'>;

let x: X = {
  x1: 'string1',
  x2: 'string2'
}

let y: Y = {
  x1: 'string1'
}

Example of Omit

Note that the properties to exclude will be checked, it is an error to exclude properties which are not defined in the specified type:

Example of Omit using non-existent property name

Tags:

Typescript