Backbencher.dev

Destructuring JavaScript Objects with TypeScript Types

Last updated on 18 Jun, 2021

Today in my project, I had to destructure an object.

const { facets, products } = response;

I wanted to give types to facets and products. Being a beginner in TypeScript, I first guessed and wrote like this:

const { facets: any, products: any } = response;

What happens above is, the value of facets attribute from response is taken and assigned to any. The correct way to do it is:

const { facets, products }: { facets: any; products: any } = category;
--- ○ ---
Joby Joseph
Web Architect