EN
TypeScript - array destructuring with rest parameter
0 points
In this article, we would like to show you how to destructure arrays with the rest parameter in TypeScript.
In the below examples we use:
- destructuring assignment syntax that allows us to extract data from arrays or objects into separate variables,
- trailing commas (or final commas) - which are also allowed on the left-hand side while using the destructuring assignment.
Simple destructuring example:
xxxxxxxxxx
1
const [a, b] = [1, 2];
2
3
console.log(a); // 1
4
console.log(b); // 2
Using rest operator:
xxxxxxxxxx
1
const [a, b, rest] = [1, 2, 3, 4, 5];
2
3
console.log(a); // 1
4
console.log(b); // 2
5
console.log(rest); // 3, 4, 5
Using trailing commas:
xxxxxxxxxx
1
const [, , , d, e] = [1, 2, 3, 4, 5];
2
3
console.log(d); // 4
4
console.log(e); // 5
Trailing commas & rest operator:
xxxxxxxxxx
1
const [, , b, rest] = [1, 2, 3, 4, 5];
2
3
console.log(b); // 3
4
console.log(rest); // 4, 5
Simple destructuring:
xxxxxxxxxx
1
interface Object {
2
a: number;
3
b: number;
4
}
5
6
const { a, b }: Object = { a: 1, b: 2 };
7
8
console.log(a); // 1
9
console.log(b); // 2
Using rest operator:
xxxxxxxxxx
1
interface Object {
2
a: number;
3
b: number;
4
c: number;
5
d: number;
6
}
7
8
const { a, b, rest } = { a: 1, b: 2, c: 3, d: 4 };
9
10
console.log(a); // 1
11
console.log(b); // 2
12
console.log(rest); // { c: 3, d: 4 }