EN
TypeScript - spread operator (...)
0 points
In this article, we would like to show you how works spread operator in TypeScript.
The spread operator allows you to spread the iterated value into its components.
Usage examples:
xxxxxxxxxx
1
const array: number[] = [1, 2, 3, 4, 5];
2
console.log(array); // 1, 2, 3, 4, 5
3
4
const text: string = 'Dirask';
5
console.log(text); // D, i, r, a, s, k
Output:
xxxxxxxxxx
1
1 2 3 4 5
2
D i r a s k
xxxxxxxxxx
1
const array: number[] = [1, 2, 3, 4, 5];
2
const array2: number[] = [array];
3
4
console.log(array2);
Output:
xxxxxxxxxx
1
[ 1, 2, 3, 4, 5 ]
xxxxxxxxxx
1
const array1: number[] = [2, 3, 4];
2
const array2: number[] = [1, array1, 5, 6, 7];
3
4
console.log(array2); // 1, 2, 3, 4, 5, 6, 7
Output:
xxxxxxxxxx
1
[ 1, 2, 3, 4, 5, 6, 7 ]
Functions like Math.max()
expect many parameters. We can't pass the array as one argument there, so we can use the spread
operator.
xxxxxxxxxx
1
const array: number[] = [1, 2, 3, 4];
2
3
console.log(Math.max(1, 2, 3, 4)); // 4
4
console.log(Math.max(array)); // 4
Output:
xxxxxxxxxx
1
4
xxxxxxxxxx
1
const object1 = {
2
x: 5,
3
y: 7,
4
};
5
6
const object2 = {
7
y: 11,
8
z: 23,
9
};
10
11
const object3 = {
12
k: 33,
13
object1,
14
object2,
15
};
16
17
console.log(object3); // { k: 33, x: 5, y: 11, z: 23 }
Note:
As we can see above, the order does matter -
y
value fromobject1
has been overwritten by value fromobject2
.
xxxxxxxxxx
1
const object1: Record<string, number> = {
2
x: 5,
3
y: 7,
4
};
5
6
const object2: Record<string, number> = {
7
y: 11,
8
z: 23,
9
};
10
11
const object3: Record<string, number> = {
12
k: 33,
13
object1,
14
object2,
15
};
16
17
console.log(object3); // { k: 33, x: 5, y: 11, z: 23 }
xxxxxxxxxx
1
interface Object1 {
2
x: number;
3
y: number;
4
}
5
6
interface Object2 {
7
y: number;
8
z: number;
9
}
10
11
interface Object3 extends Object1, Object2 {
12
k: number;
13
}
14
15
const object1: Object1 = {
16
x: 5,
17
y: 7,
18
};
19
20
const object2: Object2 = {
21
y: 11,
22
z: 23,
23
};
24
25
const object3: Object3 = {
26
k: 33,
27
object1,
28
object2,
29
};
30
31
console.log(object3); // { k: 33, x: 5, y: 11, z: 23 }
32
xxxxxxxxxx
1
type Object1 = {
2
x: number;
3
y: number;
4
};
5
6
type Object2 = {
7
y: number;
8
z: number;
9
};
10
11
type Object3 = Object1 | Object2 | {
12
k: number;
13
};
14
15
const object1: Object1 = {
16
x: 5,
17
y: 7,
18
};
19
20
const object2: Object2 = {
21
y: 11,
22
z: 23,
23
};
24
25
const object3: Object3 = {
26
k: 33,
27
object1,
28
object2,
29
};
30
31
console.log(object3); // { k: 33, x: 5, y: 11, z: 23 }