JavaScript

Object destructuring in TypeScript

Advertisements

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
JavaScript

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
JavaScript

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

interface Blog {
  title: string
  comments: number
}

const { title, comments }: Blog = blog
JavaScript

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.

Saransh Kataria

Born in Delhi, India, Saransh Kataria is the brain behind Wisdom Geek. Currently, Saransh is a software developer at a reputed firm in Austin, and he likes playing with new technologies to explore different possibilities. He holds an engineering degree in Computer Science. He also shares his passion for sharing knowledge as the community lead at Facebook Developer Circle Delhi, NCR which is a developer community in Delhi, India.

Share
Published by
Saransh Kataria

Recent Posts

How To Get The Hash of A File In Node.js

While working on a project, I wanted to do an integrity check of a file…

2 weeks ago

Native popover API in HTML

Popovers have been a problem that was typically solved by using a third-party solution. But…

3 weeks ago

Node.js 20.6 adds built-in support for .env files

Node.js 20.6 added built-in support for the .env file. This is an excellent addition to the platform…

4 weeks ago

Improve git clone performance in a CI pipeline

Have you felt particularly annoyed by the time it takes to clone a large repository,…

2 months ago

Fix: Hydration failed because the initial UI does not match what was rendered on the server

Within a React or Next.js app, if you encounter the error "Hydration failed because the…

2 months ago

How to keep the screen awake using JavaScript

Some new features in JavaScript are great to see, and the wake lock API is…

2 months ago
Advertisements