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

Extending Types in TypeScript The Right Way

Ferenc Almasi β€’ Last updated 2023 January 05 β€’ Read time 2 min read
  • twitter
  • facebook
TypeScript

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.

Copied to clipboard!
// βœ”οΈ 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.

Copied to clipboard!
type Fruit = {
  sweet: boolean
}

interface Vegetable {
  berry: boolean
}

interface Tomato extends Fruit, Vegetable {
  
}
extends can only be used with classes and interfaces

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.

  • twitter
  • facebook
TypeScript
Did you find this page helpful?
πŸ“š More Webtips
Mentoring

Rocket Launch Your Career

Speed up your learning progress with our mentorship program. Join as a mentee to unlock the full potential of Webtips and get a personalized learning experience by experts to master the following frontend technologies:

Courses

Recommended

This site uses cookies We use cookies to understand visitors and create a better experience for you. By clicking on "Accept", you accept its use. To find out more, please see our privacy policy.