TypeScript: Intersection Type Examples

Last updated on August 4, 2021 A Goodman Loading... Post a comment

Below are 2 examples of Intersection Types in TypeScript. The first one uses Interfaces and the second one uses Type Aliases.

Example 1: Intersection Types and Interfaces

The code:

// Kindacode.com

interface BudgetMeal {
  mainDish: string;
  sideDish: string;
}

interface QuickMeal {
  snack: string;
  drink: string;
}

interface FullMeal extends BudgetMeal, QuickMeal {}

const meal: FullMeal = {
  mainDish: 'Fried turkey',
  sideDish: 'Seafoam salad',
  snack: 'Mini pancake',
  drink: 'Pumpkin juice'
}

console.log(meal);

Output:

{mainDish: "Fried turkey", sideDish: "Seafoam salad", snack: "Mini pancake", drink: "Pumpkin juice"}

Example 2: Intersection Types and Type Aliases

The code:

// Kindacode.com

type SysAdmin = {
  name: string;
  privileges: string[];
}

type BackendDeveloper = {
  name: string;
  hometown: string;
  skills: string[];
}

type FrontendDeveloper = {
  name: string;
  age: number;
  skills: string[];
}

type BigBoss = SysAdmin & BackendDeveloper & FrontendDeveloper;

const boss: BigBoss = {
  name: 'Alice',
  privileges: ['playing video games in working hours'],
  hometown: 'Wonderland',
  skills: ['node.js', 'react', 'nginx'],
  age: 200
}

console.log(boss);

// Just an example
// a real boss doesn't need to be like that one

Output:

{name: "Alice", privileges: Array(1), hometown: "Wonderland", skills: Array(3), age: 200}

What’s Next?

If you’d like to learn more about modern TypeScript, take a look at the following posts:

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

You May Also Like