DEV Community

Lini Abraham
Lini Abraham

Posted on

Destructuring in TypeScript: Arrays & Objects

Destructuring is a powerful feature in JavaScript (and TypeScript) that lets you unpack values from arrays or extract properties from objects into distinct variables.

1. Array (List) Destructuring

Basic Example

const nums = [10, 20, 30];

const [first, second] = nums;

console.log(first);  // 10
console.log(second); // 20

Enter fullscreen mode Exit fullscreen mode

Skipping values

const [ , , third] = nums;
console.log(third); // 30
Enter fullscreen mode Exit fullscreen mode

Default values

const [a = 1, b = 2, c = 3] = [undefined, undefined];
console.log(a, b, c); // 1 2 3

Enter fullscreen mode Exit fullscreen mode

2. Object Destructuring

Basic Example

const user = { name: "Alice", age: 25 };

const { name, age } = user;

console.log(name); // "Alice"
console.log(age);  // 25
Enter fullscreen mode Exit fullscreen mode

Renaming variables

const { name: fullName } = user;
console.log(fullName); // "Alice"

Enter fullscreen mode Exit fullscreen mode

Default values

const { city = "Unknown" } = user;
console.log(city); // "Unknown"
Enter fullscreen mode Exit fullscreen mode

3. Nested Destructuring

const data = {
  user: {
    profile: {
      username: "bob123",
      email: "bob@example.com"
    }
  }
};

const {
  user: {
    profile: { username }
  }
} = data;

console.log(username); // "bob123"

Enter fullscreen mode Exit fullscreen mode

4. Destructuring in Function Parameters

With objects

function greet({ name, age }: { name: string; age: number }) {
  console.log(`Hello ${name}, age ${age}`);
}

greet({ name: "Charlie", age: 30 });
Enter fullscreen mode Exit fullscreen mode

With arrays

function sum([a, b]: [number, number]) {
  return a + b;
}

console.log(sum([5, 7])); // 12

Enter fullscreen mode Exit fullscreen mode

5. Combining with Rest (...)

Arrays

const [head, ...tail] = [1, 2, 3, 4];
console.log(head); // 1
console.log(tail); // [2, 3, 4]
Enter fullscreen mode Exit fullscreen mode

Objects

const { a, ...rest } = { a: 1, b: 2, c: 3 };
console.log(a);    // 1
console.log(rest); // { b: 2, c: 3 }

Enter fullscreen mode Exit fullscreen mode

Destructuring with TypeScript Types

type User = {
  id: number;
  name: string;
  email?: string;
};

const user: User = { id: 1, name: "Dana" };

const { id, name, email = "N/A" } = user;

Enter fullscreen mode Exit fullscreen mode

Top comments (0)