- Spread Оператор¶
- Apply¶
- Деструктурирование¶
- Присваивание массива¶
- Распространение объекта¶
- Заключение¶
- TypeScript — spread operator (. )
- 1. Breaking an array into individual elements:
- 2. Copying an array:
- 3. Combine arrays:
- 4. Math object.
- 5. Spread operator with objects
- Example 1
- Example 2
- Example 3
- Example 4
- Alternative titles
- How To Use The Spread Operator In TypeScript?
- The definition
- Using the spread operator with an array
- Using the spread operator with an object
- Using the spread operator with a function call
- Final thoughts
- Mastering TypeScript’s Spread Operator for Cleaner, More Flexible Code
- What is the spread operator?
- Why is this useful?
- Copying Objects/Arrays
- Arrays
- Objects
- Shallow Clones
- Merging Objects/Arrays
- Adding to objects/arrays
- But why?
- Conclusion
- Related Posts:
Spread Оператор¶
Основная задача spread оператора — это распространить элементы массива или объекта. Проще всего объяснить на примере.
Apply¶
Популярный кейс — это распространение массива в аргументы функции. Раньше вы использовали для этого Function.prototype.apply :
function foo(x, y, z) <> var args = [0, 1, 2]; foo.apply(null, args);
Сейчас вы можете сделать это, просто поставив . перед аргументами:
function foo(x, y, z) <> var args = [0, 1, 2]; foo(. args);
Здесь мы распространили массив args в аргументы функции.
Деструктурирование¶
Мы уже видели вариант использования этого оператора в деструктурировании:
var [x, y, . remaining] = [1, 2, 3, 4]; console.log(x, y, remaining); // 1,2,[3,4]
Мотивация здесь в том, чтобы упростить захватывание оставшихся элементов массива.
Присваивание массива¶
Spread оператор позволяет легко создавать расширенную версию массива в другом массиве. Это показано на примере ниже:
var list = [1, 2]; list = [. list, 3, 4]; console.log(list); // [1,2,3,4]
Вы можете поставить расширенный массив в любом месте и получить ожидаемый результат:
var list = [1, 2]; list = [0, . list, 4]; console.log(list); // [0,1,2,4]
Распространение объекта¶
Вы можете распространить один объект в другой объект. Общий случай использования — это простое добавление свойства к объекту без изменения оригинального объекта:
const point2D = x: 1, y: 2 >; /** Создание нового объекта с использованием всех свойств point2D вместе с z */ const point3D = . point2D, z: 3 >;
Для объектов положение spread оператора имеет значение. Это работает как Object.assign : то, что приходит первым, «переопределяется» тем, что приходит позже:
const point2D = x: 1, y: 2 >; const anotherPoint3D = x: 5, z: 4, . point2D >; console.log(anotherPoint3D); // const yetAnotherPoint3D = . point2D, x: 5, z: 4 >; console.log(yetAnotherPoint3D); //
Другим распространенным вариантом использования является простое поверхностное расширение:
const foo = a: 1, b: 2, c: 0 >; const bar = c: 1, d: 2 >; /** Объединение foo и bar */ const fooBar = . foo, . bar >; // fooBar теперь
Заключение¶
apply — это то, что вы часто используете в JavaScript, поэтому хорошо иметь удобный синтаксис, при котором у вас нет необходимости использовать null для this аргумента. Кроме того, наличие выделенного синтаксиса для перемещения массивов из (деструктурирование) или в (назначение) другие массивы обеспечивает аккуратный код, когда вы выполняете обработку массивов на их частях.
TypeScript — spread operator (. )
maciek211
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.
1. Breaking an array into individual elements:
const array: number[] = [1, 2, 3, 4, 5]; console.log(. array); // 1, 2, 3, 4, 5 const text: string = 'Dirask'; console.log(. text); // D, i, r, a, s, k
2. Copying an array:
const array: number[] = [1, 2, 3, 4, 5]; const array2: number[] = [. array]; console.log(array2);
3. Combine arrays:
const array1: number[] = [2, 3, 4]; const array2: number[] = [1, . array1, 5, 6, 7]; console.log(array2); // 1, 2, 3, 4, 5, 6, 7
4. Math object.
Functions like Math.max() expect many parameters. We can’t pass the array as one argument there, so we can use the spread operator.
const array: number[] = [1, 2, 3, 4]; console.log(Math.max(1, 2, 3, 4)); // 4 console.log(Math.max(. array)); // 4
5. Spread operator with objects
Example 1
const object1 = < x: 5, y: 7, >; const object2 = < y: 11, z: 23, >; const object3 = < k: 33, . object1, . object2, >; console.log(object3); //
Note:
As we can see above, the order does matter — y value from object1 has been overwritten by value from object2 .
Example 2
const object1: Record = < x: 5, y: 7, >; const object2: Record = < y: 11, z: 23, >; const object3: Record = < k: 33, . object1, . object2, >; console.log(object3); //
Example 3
interface Object1 < x: number; y: number; >interface Object2 < y: number; z: number; >interface Object3 extends Object1, Object2 < k: number; >const object1: Object1 = < x: 5, y: 7, >; const object2: Object2 = < y: 11, z: 23, >; const object3: Object3 = < k: 33, . object1, . object2, >; console.log(object3); //
Example 4
type Object1 = < x: number; y: number; >; type Object2 = < y: number; z: number; >; type Object3 = Object1 | Object2 | < k: number; >; const object1: Object1 = < x: 5, y: 7, >; const object2: Object2 = < y: 11, z: 23, >; const object3: Object3 = < k: 33, . object1, . object2, >; console.log(object3); //
Alternative titles
How To Use The Spread Operator In TypeScript?
You may have seen a mysterious syntax of three dots when you open a TypeScript file in your day-to-day coding life. This syntax is called the spread operator.
The spread operator allows to spread or expand iterable objects into individual elements.
This article explains the spread operator in TypeScript and shows many code examples.
The definition
The spread operator, added with ES6, allows to spread or expand iterable objects into individual elements. The syntax for this operator is three dots ( . ), also called an ellipsis.
Using the spread operator, a developer can:
- Copy an array/object (shallow copy).
- Merge an array/object.
- Pass an array to a function call as individual parameters.
⚠️ The spread operator is not the same as the rest operator, even though they both use the same syntax of three dots ( . ). The rest operator is the inverse of the spread operator. Instead of expanding iterable objects into individual elements, it compresses them into one.
Using the spread operator with an array
A developer can use the spread operator to copy an array in TypeScript.
typescriptconst numbers = [25,49,29]; const copy = [. numbers]; // Outputs: [25, 49, 29] console.log(copy);
As you can see, copy now contains all the elements from the array called numbers .
⚠️ However, be careful because the spread operator only does a shallow copy. It works fine if you copy primitives, but if you want to copy objects, I advise using a library that can deep-clone.
Also, using the spread operator, you can merge two arrays.
typescriptconst numbers = [25,49,29]; const numbers2 = [44,19,39]; const merged = [ . numbers, . numbers2 ]; // Outputs: [25, 49, 29, 44, 19, 39] console.log(merged);
This method works well as an alternative to the Array.concat function or the Lodash merge function.
The best Web Development course in 2023! 👉 Learn Web Development
Using the spread operator with an object
Also, you can use the spread operator to define a new object from an existing object.
typescriptconst obj1 = < a: 1, b: 2 >; const copiedObj = < . obj1 >; // Outputs: console.log(copiedObj);
In this example, we define a new object called copiedObject from the existing object called obj1 .
You can also merge multiple objects with the spread operator:
typescriptconst obj1 = < a: 1, b: 2 >; const obj2 = < c: 3, d: 4 >; const mergedObj = < . obj1, . obj2 >; // Outputs: console.log(mergedObj);
⚠️ Remember, the spread operator only does a shallow copy, so if you try to clone objects, it will cause bugs.
Using the spread operator with a function call
You can also utilize the spread operator to pass an array as individual parameters in a function call.
typescriptconst params = [ 2, 3, 4 ] as const; const add = (a: number, b: number, c: number): number => < return a + b + c; > const result = add(. params); // Outputs: 9 console.log(result);
In this example, using the spread operator, the params array we pass to the add function spreads as individual parameters.
When spreading an array in a function call, you can get this error: «A spread argument must either have a tuple type or be passed to a rest parameter.»
To fix this error, you need to:
Final thoughts
As you can see, the spread operator is great when you need to copy an array into a new array, merge two arrays, or copy object properties into a new object.
But remember that the spread operator only works well on primitive values because it does a shallow copy. If you want to clone objects, you can use a library like clone-deep
Here are some other TypeScript tutorials for you to enjoy:
The best Web Development course in 2023! 👉 Learn Web Development
Hello! I am Tim Mouskhelichvili, a Freelance Developer & Consultant from Montreal, Canada. I specialize in React, Node.js & TypeScript application development. If you need help on a project, please reach out, and let’s work together.
Mastering TypeScript’s Spread Operator for Cleaner, More Flexible Code
By Omari Thompson-Edwards Hey, I’m Omari! I’m a full-stack developer from the UK, with a passion for ReactJS. I’m an enthusiastic and hardworking junior developer, driven by a desire to learn and explore ideas. Published: 20 February 2023
The spread operator in TypeScript is a powerful feature that allows you to easily expand the contents of an array or object. This can come in handy when you need to make a copy of an existing object or array, or when you want to merge multiple arrays or objects together.
What is the spread operator?
The spread operator (…) expands any iterable object into a list of arguments. This mainly means things like arrays and objects. For example:
const myArr = [1, 2, 3]; console.log('Array'); printArgs(myArr); console.log('Spread'); printArgs(. myArr);
In the first case, we get just the one array as an argument, but in the second case, each value in the array gets provided as an argument separately.
Why is this useful?
Firstly, this means that anywhere that is expecting a list of arguments and you have an array, you can use the spread operator to transform your array. This is especially useful in TypeScript’s Math functions, which expect separate arguments rather than numbers:
const myArr = [1, 2, 3, 4, 5]; Math.max(myArr); //❌ TS2345: Argument of type 'number[]' is not assignable to parameter of type 'number'. Math.max(. myArr); //✔ 5 ️
Copying Objects/Arrays
If we take a look at the object <> and array [] syntax, these essentially accept a list of arguments as well. You might have created a new array by doing something like:
const myArr = new Array(1,2,3); //1,2,3 are arguments!
This means we can copy an object/array by turning it into a list of arguments, and then putting those arguments into a new object/array.
Arrays
const users = ['adam', 'brian', 'carl']; const newUsers = [. users]; newUsers.pop(); console.log(newUsers); //adam, brian console.log(users); //adam, brian, carl
Objects
const myObject = < foo: 'bar' >; const myNewObject = < . myObject >;
Shallow Clones
One important thing to note here is that we’re creating shallow copies. Let’s explore what that means through an example:
const adam = < money: 10 >; const brian = < money: 20 >; const usersObject = < adam, brian >; const newUsersObject = < . usersObject >;
I’ve just created a simple object, and we’re cloning it with the spread operator. Now let’s perform some actions on it:
newUsersObject.adam.money = 100; newUsersObject['adam'] = < money: 200 >;
In the clone, Adam’s money is 200, just because that’s what we’ve set it to last. So what should Adam’s money be set to in the original, 10, 100 or 200? You might expect the original should still be 10, since we cloned the array, but let’s have a look: Why has Adam changed, even though we’ve cloned the object? This is because we’ve created a shallow clone. usersObject and newUsersObject refer to two different objects, but every object in them still refers to the same object. usersObject.adam is the same object as newUsersObject.adam. In the first operation, this means we’re modifying the same object. In the second operation, since we’re actually changing what newUsersObject.adam refers to, nothing happens with the original.
Merging Objects/Arrays
You can also use the spread operator to merge two objects/arrays together. The syntax is essentially identical to cloning. For arrays:
const firstNumbers = [1, 2, 3]; const nextNumbers = [4, 5, 6]; const fullNumbers = [. firstNumbers, . nextNumbers]; //[1,2,3,4,5,6]
const foo = < foo: 'foo' >; const bar = < bar: 'bar' >; const foobar = < . foo, . bar >; //
Adding to objects/arrays
const middleNumbers = [4,5,6]; const fullNumbers = [1,2,3, . middleNumbers, 4,5,6]; //1,2,3,4,5,6,7,8,9
You can add an item anywhere around the array, and you can add any number of items. It works very similarly for objects:
But why?
For cloning, adding items, merging, etc, you might wonder why you would use the spread operator over solutions like .push(), or just setting a property. The main benefit in a lot of cases is mutability. In a lot of cases, such as when building apps with React, you may not want to modify the original array/object directly. In some cases this is fine, concat() for example does not modify the original array, but in other cases such as when pushing and popping from an array, these will modify it, whereas using spread will give you a new array.
Conclusion
That’s all! Thanks for reading this article, hopefully, you now understand how and when to use the spread operator in TypeScript. If you liked this article, feel free to leave a comment below!
Related Posts:
👋 Hey, I’m Omari Thompson-Edwards
Hey, I’m Omari! I’m a full-stack developer from the UK, with a passion for ReactJS. I’m an enthusiastic and hardworking junior developer, driven by a desire to learn and explore ideas.