Destructuring JavaScript Objects with TypeScript Types

Published 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;