2 Ways to Extend Types in TypeScript

Updated: August 16, 2022 By: Snowball Post a comment

This short and straightforward article shows you a couple of different ways to extend a type in TypeScript. Without any further ado, let’s see the code.

Using the “extends” keyword

Example:

type TypeOne = {
  a: string;
  b: number;
};

type TypeTwo = {
  c: string;
  d: string;
};

// extend TypeOne
interface InterfaceOne extends TypeOne {
  e: string;
  f: number;
}

const x: InterfaceOne = {
  a: 'KindaCode.com',
  b: 1,
  e: 'e',
  f: 2,
};

// you can also extend multiple types at once
interface InterfaceTwo extends TypeOne, TypeTwo {
  g: string;
}

const y: InterfaceTwo = {
  a: 'a',
  b: 1,
  c: 'c',
  d: 'd',
  g: 'Welcome to KindaCode.com',
};

Using the “&” operator

Example:

type TypeA = {
    a1: string;
    a2: string;
}

type TypeB = {
    b1: string;
    b2: number;
}

// Extend TypeA
type TypeAExtended = TypeA & {
    a3: string;
    a4: number;
}

// Extend both TypeA and TypeB at the same time
type TypeC = TypeA & TypeB & {
    c1: string;
    c2: number;
    c3: boolean;
}

That’s it. Further reading:

You can also check out our TypeScript category page for the latest tutorials and examples.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

Related Articles