Extending Types in TypeScript The Right Way

Ferenc Almasi • 🔄 2023 January 05 • 📖 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 {
  
}
extends can only be used with classes and interfaces
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 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.

Share on
  • twitter
  • facebook
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 less time.

Learn More

Recommended