TypeScriptInterfaces and classes
extends (interfaces)
Extending an interface with new fields, based on an existing one.
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
typealiases, the intersection gives the same effect:type Student = Person & { level: number }.
Related entries
#- extends vs implementsextends inherits fields and code from a base class, while implements only forces a class to have an interface’s methods and fields, without any of its code.
- interfaceA named description of an object’s shape that you can extend and merge.
- implementsA declaration that a class fulfills the contract described by an interface.
- Generic constraints (extends)Requiring a type parameter to match a specific shape.
Spotted a mistake or missing an example? Write to us.