Extending Types in TypeScript The Right Way
Extending types in TypeScript can be done by using the &
operator. This is called intersection types that can be used for combining two or more different types together.
// ✔️ Using different types
type Fruit = {
sweet: boolean
}
type Vegetable = {
berry: boolean
}
type Tomato = Fruit & Vegetable
// ✔️ Using interfaces
interface Fruit {
sweet: boolean
}
interface Vegetable {
berry: boolean
}
type Tomato = Fruit & Vegetable;
// ❌ This is not valid
interface Tomato = Fruit & Vegetable
The Tomato
type will now contain both fields from the other two types. You can combine as many types together this way as needed. This syntax can also be used with interfaces, however, if you want to define your type as an interface, then you will need to use the extends
keyword.
type Fruit = {
sweet: boolean
}
interface Vegetable {
berry: boolean
}
interface Tomato extends Fruit, Vegetable {
}
Notice that for extending multiple interfaces, you can comma separate them instead of using the &
operator. You also have the option to extend interfaces with types using the extends
keyword, not just interfaces, or you can even combine both of them. However, for keeping things consistent, it is recommended to stick to one or the other.

Tired of looking for tutorials?
You are not alone. Webtips has more than 400 tutorials which would take roughly 75 hours to read.
Check out our interactive course to master JavaScript in less time.
Learn MoreRecommended

How to Save Writable Store in Svelte to Local Storage
Learn how to create a persistent store in Svelte

How to Create an Infinite Scroll Component in React
With the help of the Intersection Observer API
