Exclude a Property from a Type in TypeScript

avatar

Borislav Hadzhiev

Last updated: Feb 16, 2022

banner

Photo from Unsplash

Exclude a Property from a Type in TypeScript #

Use the Omit utility type to exclude a property from a type, e.g. type WithoutCountry = Omit<Person, 'country'>. The Omit utility type constructs a new type by removing the specified keys from the existing type.

index.ts
type Person = { name: string; age: number; country: string; }; // 👇️ Type WithoutCountry = {name: string; age: number} type WithoutCountry = Omit<Person, 'country'>; const obj1: WithoutCountry = { name: 'Tom', age: 30, }; // 👇️ Type WithoutCountryAndAge = {name: string;} type WithoutCountryAndAge = Omit<Person, 'country' | 'age'>; const obj2: WithoutCountryAndAge = { name: 'Alfred', };

You can also use the Omit utility type with interfaces.

index.ts
interface Person { name: string; age: number; country: string; } // 👇️ Type WithoutCountry = {name: string; age: number} type WithoutCountry = Omit<Person, 'country'>; // 👇️ Type WithoutCountryAndAge = {name: string;} type WithoutCountryAndAge = Omit<Person, 'country' | 'age'>;

The first type we passed to Omit is the type from which we will exclude the provided one or more keys.

When you need to exclude multiple keys from a type, make sure to separate them using a pipe |.

You will often see the Omit utility type being to override the type of a specific property.

index.ts
type Person = { name: string; age: number; address: string; } // 👇️ Type T2 = {name: string; age: number; address: {country: string; city: string}} type T2 = Omit<Person, 'address'> & { address: { country: string; city: string; }; }; const obj1: T2 = { name: 'Tom', age: 30, address: { country: 'Chile', city: 'Santiago', }, };

In the example we use the Omit utility type to exclude the address property from the Person type, so we can override its type.

This is much better than duplicating the properties we need from the Person type onto T2, because we still signal to the reader of our code that there is a relation between the two types.

Had we tried to directly override the address property without excluding it from the type first, we would get an error, because there is a conflict between the type of the address property on the two types.

index.ts
type Person = { name: string; age: number; address: string; }; // 👇️ Type T2 = {name: string; age: number; address: {country: string; city: string}} type T2 = Person & { address: { country: string; city: string; }; }; const obj1: T2 = { name: 'Tom', age: 30, // ⛔️ Error: Type '{country: string; city: string}' is not assignable to type 'string' address: { country: 'Chile', city: 'Santiago', }, };
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.