How to Destructure Typed Objects in TypeScript


We’re probably familiar with object destructuring in JavaScript, as it’s been a useful tool since ES6. But how can we perform object destructuring with types while using TypeScript?

Suppose we have a response object from an API call that contains this data.

{
   gender: 'male',
   age: 6
}

We can perform basic object destructuring here.

const { gender, age } = response;

But if we’re in TypeScript, we’d want to type the variables. This is how we do that concisely.

const { gender, age }: { gender: string; age: number } = response;

However, ideally, we’d define an interface.

interface Person {
  gender: string
  age: number
}
const { gender, age }: Person = response;
const person: Person = response; // person.gender, person.age