DEV Community

TK
TK

Posted on • Edited on • Originally published at leandrotk.github.io

1 1

Typescript Learnings 001: Object Destructuring

This is part of my series on Typescript Learnings, where I share micro posts about everything I'm learning related to Typescript.

And it was first published at TK's blog.

It's a common feature to destructure objects in JavaScript. For example, imagine we have a Person object. It looks like:

const person = {
  firstName: 'TK',
  age: 24,
  email: 'tk@mail.com',
  isLearning: true
};
Enter fullscreen mode Exit fullscreen mode

And when we use it, sometimes we want to destructure the object to get the attributes.

const { firstName, age, email, isLearning } = person;
Enter fullscreen mode Exit fullscreen mode

In Typescript, it works the same way. But with types. So let's type the attributes. At first I thought I could add the type after each attribute. Something like:

const { firstName: string, age: number, email: string, isLearning: boolean } = person;
Enter fullscreen mode Exit fullscreen mode

But it actually doesn't compile that way. We don't specify a type for each attribute, we specify the object type. We could add this way:

const {
  firstName,
  age,
  email,
  isLearning
}: {
  firstName: string,
  age: number,
  email: string,
  isLearning: boolean
} = person;
Enter fullscreen mode Exit fullscreen mode

Or we could have a Person type (or interface) to handle these types.

type Person = {
  firstName: string,
  age: number,
  email: string,
  isLearning: boolean
};
Enter fullscreen mode Exit fullscreen mode

And use it in the object destructuring:

const { firstName, age, email, isLearning }: Person = person;
Enter fullscreen mode Exit fullscreen mode

Implementing a type is cool because we could also use it in the person definition:

const person: Person = {
  firstName: 'TK',
  age: 24,
  email: 'tk@mail.com',
  isLearning: true
};
Enter fullscreen mode Exit fullscreen mode

Resources

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post →

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

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

Okay