Object destructuring with TypeScript

Find out how to destructure objects with types or interfaces in TypeScript.
June 10, 2021TypeScript
2 min read

Object destructuring in JavaScript allows us to unpack values from arrays, or properties from objects, into specific and distinct variables.

Object destructuring in JavaScript uses a destructuring assignment syntax.

We can use TypeScript to specify the type of the object being destructured. Let's first take a look at how object destructuring is done in JavaScript. Then, we'll see how we can enhance object destructuring by using TypeScript.

const player = {
  firstName: 'Roger',
  lastName: 'Federer',
  age: 36,
};

const { firstName, lastName } = player;

console.log(firstName); // Roger
console.log(lastName); // Federer

What if we are using TypeScript and want to apply types to the destructuring of objects? Let's take a look at how we can do it.

const { firstName, lastName }: { firstName: string; lastName: string } = player;

console.log(firstName); // Roger
console.log(lastName); // Federer

We can simplify this example by creating a type or interface for what we are destructuring, which are the firstName and lastName properties in this case.

const player = {
  firstName: 'Roger',
  lastName: 'Federer',
  age: 36,
};

interface PlayerName {
  firstName: string;
  lastName: string;
}

const { firstName, lastName }: PlayerName = player;

console.log(firstName); // Roger
console.log(lastName); // Federer

We created a PlayerName interface that we then used to specify the type of the object being destructured.

As you can see, TypeScript makes object destructuring more transparent and more predictable.

We also get the added benefit of validation. If we try to destructure an object property that does not actually belong to PlayerName, the TypeScript compiler will indicate an error at that line number.

New
Be React Ready

Learn modern React with TypeScript.

Learn modern React development with TypeScript from my books React Ready and React Router Ready.