DEV Community

Cover image for Object destructuring in TypeScript
saransh kataria
saransh kataria

Posted on • Originally published at wisdomgeek.com

7

Object destructuring in TypeScript

Object destructuring is a powerful ES 6 feature that can help developers write cleaner code. It allows us to extract properties from a JavaScript object into variables.

If you are unfamiliar with it, read our post about object destructuring to know more about what is possible using it.

When it comes to object destructuring in TypeScript, the following statement doesn’t work.

const { title: string, comments: number } = blog
Enter fullscreen mode Exit fullscreen mode

Technically, the way it works is that it assigns the title property of the object to a variable named string and the comments property to the number variable. This happens because JavaScript assumes that we want to destructure and rename the variables, which is valid ES6 syntax.

The right way to do object destructuring in TypeScript would be

const { title, comments } : { title: string; comments: number }  = blog
Enter fullscreen mode Exit fullscreen mode

Another alternative can be to use an interface or a type declaration:

interface Blog {
  title: string
  comments: number
}

const { title, comments }: Blog = blog
Enter fullscreen mode Exit fullscreen mode

By default, the types usually get inferred, and this type of object destructuring is usually not needed. But for the cases when we do, we now know how to. I hope this post was helpful. If you have any questions, feel free to drop a comment below.

Originally published at https://www.wisdomgeek.com on March 28, 2024.

Top comments (2)

Collapse
 
khaybee24 profile image
khaybee24

this is a good one

Collapse
 
saranshk profile image
saransh kataria

thank you for leaving a comment. Glad it was helpful!

11 Tips That Make You a Better Typescript Programmer

typescript

1 Think in {Set}

Type is an everyday concept to programmers, but it’s surprisingly difficult to define it succinctly. I find it helpful to use Set as a conceptual model instead.

#2 Understand declared type and narrowed type

One extremely powerful typescript feature is automatic type narrowing based on control flow. This means a variable has two types associated with it at any specific point of code location: a declaration type and a narrowed type.

#3 Use discriminated union instead of optional fields

...

Read the whole post now!

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay