Extending Types in TypeScript The Right Way

Ferenc Almasi • 2022 September 20 • 📖 2 min read

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
Copied to clipboard!

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 {
  
}
Copied to clipboard!

Notice that for extending multiple interfaces, you can comma separate them instead of using the & operator. You also have the option to extend 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.

JavaScript Course Dashboard

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 5 hours.

Learn More

📚 Get access to exclusive content

Want to get access to exclusive content? Support webtips with the price of a coffee to get access to tips, checklists, cheatsheets, and much more. ☕

Get access Support us
Read more on
🎉 Thank you for subscribing to our newsletter. x