How to add types to an interface from another interface or extend types in TypeScript?

Published January 9, 2022

To add types to an interface from another interface (aka extending the types) in TypeScript, you can use the extends keywords after the interface name followed by the name of the interface to get the types from.

TL;DR

// a simple interface
interface PersonalDetails {
  name: string;
  age: number;
}

// another simple interface
// which extends the `PersonalDetails` interface
interface AllDetails extends PersonalDetails {
  salary: number;
  isAdmin: boolean;
}

// a simple object using
// the extended `AllDetails` interface
const johnDetails: AllDetails = {
  name: "John Doe",
  age: 25,
  salary: 30000,
  isAdmin: true,
}; // ✅ valid and satisfies the interface.

For example, let's say we have an interface called PersonalDetails like this,

// a simple interface
interface PersonalDetails {
  name: string;
  age: number;
}

Now let's also consider another interface called AllDetails like this,

// a simple interface
interface PersonalDetails {
  name: string;
  age: number;
}

// another simple interface
interface AllDetails {
  salary: number;
  isAdmin: boolean;
}

Now to get the types from the PersonalDetails interface to the AllDetails interface we can use the extends keyword after the AllDetails interface name then followed by the name of the interface to get the types from. In our case, it is the PersonalDetails interface.

It can be done like this,

// a simple interface
interface PersonalDetails {
  name: string;
  age: number;
}

// another simple interface
// which extends the `PersonalDetails` interface
interface AllDetails extends PersonalDetails {
  salary: number;
  isAdmin: boolean;
}

We have successfully extended all the types from the PersonalDetails interface into the AllDetails interface and is now available to be used.

This is useful since we don't have to write the types by ourselves manually again.

Now let's use the AllDetails interface on an object like this,

// a simple interface
interface PersonalDetails {
  name: string;
  age: number;
}

// another simple interface
// which extends the `PersonalDetails` interface
interface AllDetails extends PersonalDetails {
  salary: number;
  isAdmin: boolean;
}

// a simple object using
// the extended `AllDetails` interface
const johnDetails: AllDetails = {
  name: "John Doe",
  age: 25,
  salary: 30000,
  isAdmin: true,
}; // ✅ valid and satisfies the interface.

As you can see TypeScript accepts the object structure since it is valid and satisfies the AllDetails interface which confirms that the extends keyword is working correctly.

See the above code live in codesandbox.

That's all 😃!

Feel free to share if you found this useful 😃.


Share on: Facebook Twitter