destructuring in typescript

Destructuring is a way to extract values from objects and arrays into distinct variables. It is a shorthand syntax in TypeScript and ES6 that can be used to assign values from an array or object to variables.

Array destructuring:

index.ts
const [first, second, third] = [1, 2, 3];
console.log(first); // Output: 1
console.log(second); // Output: 2
console.log(third); // Output: 3
142 chars
5 lines

Object destructuring:

index.ts
const user = { name: 'John', age: 30 };
const { name, age } = user;
console.log(name); // Output: John
console.log(age); // Output: 30
135 chars
5 lines

Destructuring with default values:

index.ts
const [first, second, third = 3] = [1, 2];
console.log(first); // Output: 1
console.log(second); // Output: 2
console.log(third); // Output: 3
143 chars
5 lines

Nested destructuring:

index.ts
const user = { id: 1, name: 'John', age: 30, address: { city: 'New York', zip: 10001 } };
const { name, address: { city } } = user;
console.log(name); // Output: John
console.log(city); // Output: New York
206 chars
5 lines

gistlibby LogSnag