๐ŸŽ“ A1Learner
๐Ÿ”
0 of 33 lessons completed

TypeScript Extending Types

Extending a type builds a new type from an existing one. An interface can extend another interface, and aliases can combine into an intersection.

Extend an interface

Employee extends Person. An Employee value holds both the name and the salary.

interface Person {
  name: string;
}

interface Employee extends Person {
  salary: number;
}

const worker: Employee = { name: "Ada", salary: 5000 };
console.log(worker.name);
console.log(worker.salary);

Combine with an intersection

The ampersand combines two aliases into one type. The value must match both aliases.

type Named = {
  name: string;
};

type Aged = {
  age: number;
};

type PersonInfo = Named & Aged;

const person: PersonInfo = { name: "Ben", age: 41 };
console.log(person.name);
console.log(person.age);

Example

interface Person {
  name: string;
}

interface Manager extends Person {
  team: string;
}

type Contact = {
  email: string;
};

type ReachableManager = Manager & Contact;

const lead: ReachableManager = { name: "Ada", team: "Core", email: "ada@example.com" };
console.log(lead.name);
console.log(lead.team);
console.log(lead.email);

Key points

  • The extends keyword gives a child interface every member of its parent.
  • A child interface adds members of its own.
  • An intersection combines two types into one type.
  • A value of an intersection type must satisfy every combined type.
  • Extending a type reuses a shape instead of writing it again.

In this example, Manager extends Person and adds a team field. The Contact alias holds an email field. The intersection combines Manager and Contact into one type. The lead value carries all three fields.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท TypeScript Playground

Exercise

What does the ampersand in a type do?