Object destructuring with types in TypeScript

Jun 30, 2023#typescript

Object destructuring is a powerful feature of JavaScript and TypeScript that can help you write cleaner and more expressive code. This syntax allows you to extract properties from an object and assign them to variables or parameters.

You can use object destructuring to create variables, assign default values, rename properties, or omit some properties.

// An object with two properties
const person = { name: "Alice", age: 25, hobby: "reading" };

// Destructuring the name and hobby properties and assigning default values
const { name, hobby = "reading" } = person;

// Destructuring the name property and omitting the rest
const { name, ...others } = person;

// Destructuring the name and age properties and renaming them to firstName and years
const { name: firstName, age: years } = person;

In TypeScript, you can also specify the type of the object or the properties that you are destructuring. There are two ways to do this:

  • You can use a type annotation after the destructuring pattern, like this:
const { name, age }: { name: string; age: number } = person;

This tells TypeScript that the object you are destructuring has two properties, name and age, and they are both of type string and number respectively.

  • You can use an interface or a type alias to define the shape of the object, and then use it as a type annotation, like this:
interface Person {
  name: string;
  age: number;
}

const { name, age }: Person = person;

This tells TypeScript that the object you are destructuring conforms to the Person interface, which has two properties, name and age, of type string and number respectively.

Using an interface or a type alias can be more convenient and reusable than writing the type annotation inline, especially if you have complex or nested objects.

You can also use object destructuring in function parameters, which can make your code more concise and readable. For example, instead of writing a function like this:

function greet(person: Person) {
  console.log(`Hello ${person.name}, you are ${person.age} years old.`);
}

You can write it like this:

function greet({ name, age }: Person) {
  console.log(`Hello ${name}, you are ${age} years old.`);
}

This way, you don’t have to repeat the person parameter inside the function body, and you can directly access the name and age properties.