Spread operator in typescript

Spread operator in typescript

In Typescript, you can use spread operator to spread the element of an array or object. The spread operator can be used for initializing an array or object from another array or object. You can also use spread operator for object destructuring.

To read more about object destructuring , you can follow below link:

Let’s explore some of the examples of Spread operators.

Spread Operator Examples

Learn how to initialize array from another array

Create new array from existing array.

let Array1 = [1, 2, 3]; //1,2,3 let Array2 = [4, 5, 6]; //4,5,6 //Create new array from existing array let copyArray = [. Array1]; //1,2,3 //Create array by merging two arrays let mergedArray = [. Array1, . Array2]; //1,2,3,4,5,6 //Create new array from existing array + more elements let newArray = [. Array1, 7, 8]; //1,2,3,7,8 

Expanded version of an array into another array

var list = [1, 2]; list = [. list, 3, 4]; console.log(list); // [1,2,3,4] //put expanded array at any position var list = [1, 2]; list = [0, . list, 4]; console.log(list); // [0,1,2,4] 

A Better way to concatenate arrays

var arr1 = [0, 1, 2]; var arr2 = [3, 4, 5]; // concatenate array using concat() arr1 = arr1.concat(arr2); //concate array using spread var arr1 = [0, 1, 2]; var arr2 = [3, 4, 5]; arr1 = [. arr1, . arr2]; // arr1 is now [0, 1, 2, 3, 4, 5] 

Learn how to initialize object from another object

Similarly, you can create new object from existing object.

let Object1 =  a: 1, b: 2, c: 3 >; // let Object2 =  d: 4, e: 5, f: 6 >; // //Create new object from existing object let copyObject =  . Object1 >; // //Create new object from existing object + more elements let newObject =  . Object1, g: 7, h: 8 >; // //Create object by merging two objects let mergedObject =  . Object1, . Object2 >; // 

Spread operator in Object Destructuring

The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.

function myFunc(x, y, z)  console.log(x); console.log(y); console.log(z); > var paramArray = [0, 1, 2]; myFunc(. paramArray); //10, 20, 30 

Object Spread

You can simply add a property to an object without mutating the original.

const point1 =  x: 1, y: 2 >; /** Create a new object by using all the point1 properties along with z */ const point2 =  . point1, z: 3 >; 

Note: For objects, the order of where you put the spread matters. What comes first is ‘overridden’ by what comes later.

const point1 =  x: 1, y: 2 >; const newPoint1 =  x: 5, z: 4, . point1 >; console.log(newPoint1); // const newPoint2 =  . point1, x: 5, z: 4 >; console.log(newPoint2); // 

Summary

So, in summary, we learn how we can use spread operator to spread an array or object elements. I tried to give a lot of useful example of using the spread operator in your TypeScript code. It is really fun to play with spread operator.

Источник

TypeScript / JavaScript Spread Operator

The spread operator (in the form of ellipsis) can be used in two ways:

The spread operator is most widely used for method arguments in the form of rest parameters where more than 1 value is expected. A typical example can be a custom sum(. args) method which can accept any number of method arguments and add them to produce the sum.

function sum(. args: number[]) < return args.reduce((sum, current) =>sum + current, 0); > //function can be invoked with any number of parameters sum(); //0 sum(1); //1 sum(1, 2); //3 sum(1, 2, 3, 4); //10

2. Spread Operator Example

Let us check out a few examples of the spread operator to understand its usage better.

2.1. Initialize a New Array from Another Array

We can use the spread operator to create arrays from existing arrays in the given fashion.

let origArrayOne = [ 1, 2, 3]; //1,2,3 let origArrayTwo = [ 4, 5, 6]; //4,5,6 //Create new array from existing array let copyArray = [. origArrayOne]; //1,2,3 //Create new array from existing array + more elements let newArray = [. origArrayOne, 7, 8]; //1,2,3,7,8 //Create array by merging two arrays let mergedArray = [. origArrayOne, . origArrayTwo]; //1,2,3,4,5,6

2.2. Initialize a New Object from Another Object

We can also use the spread operator to create objects from the existing objects in the given fashion.

let origObjectOne = ; // let origObjectTwo = ; // //Create new object from existing object let copyObject = ; // //Create new object from existing object + more elements let newObject = ; // //Create object by merging two objects let mergedObject = ; //

The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.

function myFunction(x, y, z) < console.log( x ); console.log( y ); console.log( z ); >var parametersArray = [0, 1, 2]; myFunction(. parametersArray); //0, 1, 2

3. Difference between Spread Operator and apply() Method

The JavaScript’s apply() method calls a function with a given this value, and arguments provided as an array .
For example, in the below example, both highlighted function calls are equivalent. They both print the same output.

The Spread operator (part of ECMAScript 6) is a better version of the apply() method. Using the spread operator, we can write the above statement as given below.

var numbers = [1, 2, 3, 4, 5]; console.log.apply(console, numbers); //1 2 3 4 5 console.log(. argsArray); //1 2 3 4 5

Источник

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!

👋 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.

Источник

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

Источник

Читайте также:  Import url common css
Оцените статью