Object Destructuring with Types in TypeScript
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:
1 | const { name, age } = body.value; |
However, I encountered an issue when trying to add types to the destructured variables:
1 | 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:
1 | 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:
1 | interface Dog { |
With this type or interface defined, a shorter syntax can be used:
1 | const dog: Dog = body.value; |
By following this approach, you can effectively destructure objects while ensuring the correct assignment of types in TypeScript.
tags: [“TypeScript”, “Deno”, “object destructuring”]