extends (interfaces)

Extending an interface with new fields, based on an existing one.

On this page

Example

#
TypeScript
interface Person {
  name: string
  email: string
}

interface Student extends Person {
  level: number
}

interface Mentor extends Person {
  specialization: string
}

const student: Student = { name: 'Mia', email: 'mia@example.com', level: 3 }
const mentor: Mentor = { name: 'Noah', email: 'noah@example.com', specialization: 'React' }

console.log(`${student.name} is learning with ${mentor.name} (${mentor.specialization})`)
Result
Mia is learning with Noah (React)

Definition and usage

#

The extends keyword lets you build an interface on top of another one. The new interface inherits all the base interface’s fields and adds its own. You can extend several interfaces at once by listing them separated by commas.

That way you avoid repeating fields shared by multiple types. For example, Student and Mentor can both extend a shared Person with a name and an email address.

An extending interface can narrow the type of a base field (for example from string to a union of literals), but it can’t change it to something incompatible.

Syntax

#
Syntax
interface Derived extends Base, Second {
  newField: type
}

Good practices

#
  • Pull shared fields out into a base interface, but don’t build deep hierarchies. Two or three levels are enough.
  • With type aliases, the intersection gives the same effect: type Student = Person & { level: number }.

Related entries

#

Spotted a mistake or missing an example? Write to us.