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
...operatingValueExample 1: Creating a Shallow Copy of an Array
The below code implements the spread operator to create a shallow copy of an array.
let oldArray: number[] = [1, 2, 3];
let newArray: number[] = [...oldArray];
console.log(newArray);
Output:
[1, 2, 3]Example 2: Combining Elements of Two Arrays
The below code combines the elements of two different arrays into a single array using spread operator.
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: Creating a Shallow Copy of an Object
The below code implements the spread operator to create a shallow copy of an object.
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 4: Modifying a Property of an Object
The below code modifies the value of an property of an object using spread operator.
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
}Conclusion
The spread operator in TypeScript simplifies array and object manipulation by enabling easy copying, combining, and property modification. Its concise syntax enhances code readability and efficiency, making it an essential tool for modern TypeScript development.