Extend an interface as not Required in TypeScript

avatar

Borislav Hadzhiev

Last updated: Feb 15, 2022

banner

Photo from Unsplash

Extend an interface as not Required in TypeScript #

Use the Partial utility type to extend an interface as not required, e.g. interface SpecificLocation extends Partial<Location> {}. The Partial utility type constructs a new type with all of the properties of the provided type set to optional.

index.ts
interface Location { address: string; } interface SpecificLocation extends Partial<Location> { x: number; y: number; } const example: SpecificLocation = { x: 5, y: 10, };

The Partial utility type allows us to set all of the properties of a specific type to optional.

We passed the Location interface to the Partial utility type when extending it, so we are not required to set the address property when using the SpecificLocation type.

If you only need to set some of the properties of the interface to optional when extending it, you can:

  1. Use the Omit utility type to remove one or more properties from the interface.
  2. Combine Partial with the Pick utility type.
index.ts
interface Location { address: string; country: string; } interface SpecificLocation extends Omit<Location, 'address'>, Partial<Pick<Location, 'address'>> { x: number; y: number; } const example: SpecificLocation = { country: 'Chile', x: 5, y: 10, };

The example looks a bit nasty, but is not difficult to reason about.

The first thing we did was create a new interface based on the Location interface, for which the address property is omitted.

We used the Pick utility type to get the type of the address property from the Location interface and set it to optional with the Partial utility type.

In the SpecificLocation interface, the country property is required, but the address property is set to optional.

If you have to do this with multiple properties, you should separate them with a pipe | when passing them to the utility types.

index.ts
interface Location { address: string; country: string; city: string; } interface SpecificLocation extends Omit<Location, 'address' | 'city'>, Partial<Pick<Location, 'address' | 'city'>> { x: number; y: number; } const example: SpecificLocation = { country: 'Chile', x: 5, y: 10, };

In the example above, we set the address and city properties to optional when extending the interface, however the country property is still set to required.

This approach is much better than duplicating the same properties between multiple interfaces, because we still signal to the reader of our code that there is a connection between the two interfaces.

If we just duplicated the properties and set them to not required, we would lose the connection between the interfaces.

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.