DEV Community

Cover image for Combine Objects In TypeScript
Kyle TechSquidTV
Kyle TechSquidTV

Posted on

Combine Objects In TypeScript

If you Google how to combine multiple objects into a single object with shared properties, you will get some information back on using the spread operator. Let's look at a basic example of the spread operator with TypeScript.

In this example, we will be creating Super Heros by combining our regular Heros with SuperPowers to result in a single Super Hero.

Begin by creating an Interface for each of the two objects. One object should ideally contain all of the required properties, and our secondary object should contain only optional properties.

Our Hero will be the base object which we will later combine with Super Powers.

interface Hero {
  class: "human" | "elf" | "orc",
  baseHealth: number
}
Enter fullscreen mode Exit fullscreen mode

Our secondary object Interface, SuperPowers will contain only optional properties describing our possible superpowers.

interface SuperPowers {
  flying?: boolean,
  superSpeed?: boolean,
  strengthMultiplier?: number
}

Enter fullscreen mode Exit fullscreen mode

Now, if our human Hero were to fall into a vat of nuclear waste we can only assume they would potentially gain Super Powers. Let's describe an object with the properties of both.

interface SuperHero extends Hero, SuperPowers {}
Enter fullscreen mode Exit fullscreen mode

Our SuperHero interface simply extends both of our prior definitions, effectively adding them together into this new Interface.

Now we have our definitions, let's create our new human Hero and an object containing the SuperPowers we plan to add to our human Hero later.

const human: Hero = {class: "human", baseHealth: 100}
const powers: SuperPowers = {flying: true}
Enter fullscreen mode Exit fullscreen mode

Time to combine. Our Hero has fallen into a vat of nuclear waste, what emerges will no longer be a Hero, but a SuperHero.

const superMan: SuperHero = {...human, ...powers}
Enter fullscreen mode Exit fullscreen mode

superMan will have the following types:

  • baseHealth
  • class
  • flying?
  • strengthMultiplier?
  • superSpeed?

Full example

interface Hero {
  class: "human" | "elf" | "orc",
  baseHealth: number
}

interface SuperPowers {
  flying?: boolean,
  superSpeed?: boolean,
  strengthMultiplier?: number
}

interface SuperHero extends Hero, SuperPowers {}

const human: Hero = {class: "human", baseHealth: 100}
const powers: SuperPowers = {flying: true}

const superMan: SuperHero = {...human, ...powers}

Enter fullscreen mode Exit fullscreen mode

TypeScript Playground: TS Playground
Spread Syntax: MDN Spread Syntax

Top comments (0)