When working with TypeScript in Deno, I came across the need to destructure an object. Although I was familiar with the basics of TypeScript, object destructuring posed a challenge for me.

Initially, I attempted to destructure the object using the following syntax:

const { name, age } = body.value;

However, I encountered an issue when trying to add types to the destructured variables:

const { name: string, age: number } = body.value;

Despite appearing to work, this syntax actually assigns the value of the name property to a variable named string, and the value of the age property to a variable named number.

To correctly assign types during object destructuring, the following syntax should be used:

const { name, age }: { name: string; age: number } = body.value;

A better approach is to create a type or interface for the object’s data. For example:

interface Dog {
  name: string;
  age: number;
}

With this type or interface defined, a shorter syntax can be used:

const dog: Dog = body.value;

By following this approach, you can effectively destructure objects while ensuring the correct assignment of types in TypeScript.