How to extend a Type in TypeScript

avatar

Borislav Hadzhiev

Last updated: Feb 15, 2022

banner

Photo from Unsplash

Extend a Type in TypeScript #

Use an intersection type to extend a type in TypeScript, e.g. type TypeB = TypeA & {age: number;}. Intersection types are defined using an ampersand & and are used to combine existing object types. You can use the & operator as many times as necessary to construct a type.

index.ts
type TypeA = { name: string; }; type TypeB = TypeA & { age: number; }; type TypeC = TypeB & { country: string; }; const example: TypeC = { name: 'Tom', age: 30, country: 'Chile', };

Intersection types are defined by using the & operator and allow us to extend existing object types.

You can add properties to the type inline or use it to combine existing object types.

index.ts
type TypeA = { name: string; }; type TypeB = { age: number; country: string; }; type TypeC = TypeA & TypeB; const example: TypeC = { name: 'Tom', age: 30, country: 'Chile', };

You can use the & operator to extend the object type with an already defined interface as well.

index.ts
type TypeA = { name: string; age: number; }; interface InterfaceA { country: string; } type TypeB = TypeA & InterfaceA; const example: TypeB = { name: 'Tom', age: 30, country: 'Chile', };

You can use the & operator as many times as necessary to construct a type.

index.ts
type TypeA = { name: string; }; type TypeB = { country: string; }; type TypeC = { age: number; }; type TypeD = TypeA & TypeB & TypeC; const example: TypeD = { name: 'Tom', age: 30, country: 'Chile', };

If you have to extend an interface with a type, you have to use the extends keyword.

index.ts
type TypeA = { name: string; country: string; }; interface InterfaceA extends TypeA { age: number; } const example: InterfaceA = { name: 'Tom', age: 30, country: 'Chile', };

If you have to extend an interface with multiple types, separate the types with a comma.

index.ts
type TypeA = { name: string; }; type TypeB = { country: string; }; interface InterfaceA extends TypeA, TypeB { age: number; } const example: InterfaceA = { name: 'Tom', age: 30, country: 'Chile', };

An easy way to think about the & operator and the extends keyword is - we are copying members from other named types and adding any new members we want to a type.

Extending a type is useful, because it signals to the reader of the code that the types are related in some way.
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.