2
4

TypeScript: How to Perform Object Destructuring with Types

Reading Time: 2 minutes

To perform object destructuring with types, there are 3 methods available. Let’s look into them here.

JavaScript

In JavaScript, we can easily perform destructuring by placing the attribute names inside the braces to extract the value out.

Below show the illustration in JavaScript. Thus, in order to make it easier to compare, we will be using the same input and output to show in TypeScript.

const person = {
  name: 'my-name',
  age: 11,
  height: 160,
};

const { name, age } = person;

console.log(name); // "my-name"
console.log(age);  // 11

For more illustration on JavaScript object destructuring, we have an article here.

Methods to Perform Object Destructuring with Types

  • Inline Casting
  • Using Interface Declaration
  • Using Type Declaration

Inline Casting

Inline casting method have 2 sections. The first section is to define the attribute we want to extract. While the 2nd section is to define the datatype casting to the attribute. Subsequently, these 2 sections will be join by a colon.

Here, we cast string type to name and number type to age.

const person = {
  name: 'my-name',
  age: 11,
  height: 160,
};

const { name, age }: { name: string, age: number } = person;

console.log(name); // "my-name"
console.log(age);  // 11

This method also allow rename to be done together. Notice that in the illustration below, we add new naming of the variable beside the original naming.

const { name: newName, age: newAge }: { name: string, age: number } = person;

console.log(newName); // "my-name"
console.log(newAge);  // 11

Using Interface Declaration

This method require us to create an interface of a new object with the attributes we want to extract. The advantage of this is that we can always export it and reuse in other places!

Below is the illustration showing the implementation and usage.

const person = {
  name: 'my-name',
  age: 11,
  height: 160,
};

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

const { name, age }: NewPerson = person;

console.log(name); // "my-name"
console.log(age);  // 11

Using Type Declaration

This method require us to create the attributes as a type. We can also export this and reuse in other places!

const person = {
  name: 'my-name',
  age: 11,
  height: 160,
};

type NewPerson = { name: string; age: number; };

const { name, age }: NewPerson = person;

console.log(name); // "my-name"
console.log(age);  // 11

Conclusion

Out of the 3 methods we have discuss above, type and interface method has the most readable style and will also provide the ability to reuse if we need to export it.

Show Comments

No Responses Yet

Leave a Reply