How to use Spread Operator in TypeScript ?

The spread operator in Typescript, denoted by three dots (`…`), is a powerful tool, that allows you to spread the elements of an array or objects into another array or objects. This operator makes it easy to copy arrays, combine arrays, or create shallow copies of iterable.

Syntax

...operatingValue

Example 1: The below code implements the spread operator to create a shallow copy of an array.

Javascript




let oldArray: number[] = [1, 2, 3];
let newArray: number[] = [...oldArray];
console.log(newArray);


Output:

[1, 2, 3]

Example 2: The below code combines the elements of two different arrays into a single array using spread operator.

Javascript




let array1: number[] = [1, 2];
let array2: number[] = [3, 4];
let mergedArray: number[] =
    [...array1, ...array2];
 
console.log(mergedArray);


Output:

[1, 2, 3, 4]

Example 3: The below code implements the spread operator to create a shallow copy of an object.

Javascript




type objType = {
    name: string,
    age: number
}
 
let oldObject: objType =
    { name: 'Author', age: 25 };
let newObject: objType =
    { ...oldObject };
 
console.log(newObject);


Output:

{
name: 'Author',
age: 25
}

Example: The below code modifies the value of an property of an object using spread operator.

Javascript




type objType = {
    name: string,
    age: number
}
 
let initialObject: objType =
    { name: 'Author', age: 23 };
let modifiedObject: objType =
    { ...initialObject, age: 24 };
 
console.log(modifiedObject);


Output:

{    
name: 'Author',
age: 24
}


Contact Us