πŸ’‘ This page contain affiliate links. By making a purchase through them, we earn a commission at no extra cost to you.

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, which 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 following best practices and keeping things consistent, it is recommended to stick to one or the other.

Did you find this page helpful?
πŸ“š More Webtips
Frontend Course Dashboard
Master the Art of Frontend
  • check Unlimited access to hundred of tutorials
  • check Access to exclusive interactive lessons
  • check Remove ads to learn without distractions
Become a Pro

Recommended