DEV Community

Carlo Miguel Dy
Carlo Miguel Dy

Posted on

How to share properties from an Interface to a new Interface with TypeScript


I just saw somewhere in an FB Community group asking how they are able to share the properties from a User interface to a PublicUser interface.

I have answered the person who asked the question and I'd also like to share my answer in this post.


Given that you have a User interface with the following properties that describes the model/entity.

interface User {
  name: string;
  email: string;
  age?: number;
Enter fullscreen mode Exit fullscreen mode

And you also want these properties in a new interface, for example for a Customer interface we will extend the User interface

interface Customer extends User {
  phoneNumber: string;

  address?: {
    streetAddress: string;
  } | null;
Enter fullscreen mode Exit fullscreen mode

By doing that we will have the name, email, age fields inherited into our new interface which is the Customer interface.

So as an example I will attach a screenshot below.


To break it down for you, we created an object and gave it a type of Customer interface, so by triggering or to peek which properties are available in Visual Studio Code (with CTRL + Space) it shows that the properties from User interface are inherited over to the Customer interface.



With that in mind instead of having to copy all properties from the User interface and paste it into the Customer interface, we have just inherited it into the Customer interface from the User interface. So we are writing lesser code.

That's all I have. Hope this was useful!

Top comments (0)