Add a property to an existing Type in TypeScript

avatar

Borislav Hadzhiev

Last updated: Mar 21, 2022

banner

Photo from Unsplash

Add a property to an existing Type in TypeScript #

Use an intersection type to add a property an an existing type in TypeScript, e.g. type Person = Employee & {myProperty: string}. Intersection types allow us to build up new types by extending them and are most commonly used to combine existing object types.

index.ts
type Employee = { id: number; name: string; }; // 👇️ use intersection type type Person = Employee & { country: string; }; const person: Person = { id: 1, name: 'Tom', country: 'Germany', };

An intersection type is defined using the ampersand & operator.

index.ts
type A = { a: string; }; type B = { b: string; }; // type Combined = { // a: string; // b: string; // } type Combined = A & B; const combined: Combined = { a: 'hello', b: 'world', };

Intersection types allow us to build up new types by extending them and are most commonly used to combine existing object types.

You could use an intersection type with type aliases or interfaces.

index.ts
interface Employee { id: number; } type Person = { name: string; }; type Developer = Employee & Person & { language: string; }; const dev: Developer = { id: 1, name: 'Tom', language: 'TypeScript', };

You can use as many intersection types as necessary to construct the final type.

If you need to override the type of a specific property, use the Omit utility type.

index.ts
type Person = { id: number; name: string; country: string; }; type Employee = Omit<Person, 'id'> & { id: string; // 👈️ override type of id property salary: number; }; const emp: Employee = { id: 'employee-number-1', name: 'Tom', salary: 100, country: 'Germany', };

The Person type has an id property of type number and we need to change the property's type to string.

If we want to override its type, we have to remove the property from the Person type first.

The main benefits of using intersection types are:

  1. Reducing duplication, because we don't have to copy properties between interfaces.
  2. Signaling intent to the reader of our code that there is a relation between the two types.
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.