Programmers frequently need to pass an array as a parameter to a function or method. Similar to JavaScript, TypeScript allows passing an array as a parameter. However, TypeScript has additional features that permit the developers to specify the types of elements in an array, which makes the code more type-safe, simple, and easy to maintain.
This article will discuss the procedure to pass an array as a parameter in TypeScript.
How Can I Pass an Array in TypeScript?
To pass an array as a parameter in TypeScript, simply declare the parameter as an array type. You can pass single or multi-typed arrays to a function by just specifying the type.
Syntax
For passing an array in a function, use the below-given syntax:
// code
}
Example 1: Pass Single-Type Array
In the given example, we will pass a single-typed array to a function as a parameter and perform an operation on it. Here, we will define a function “sum” that takes a “number” type array and returns the sum of all the elements:
let sum = 0;
for (let elem of array) {
sum += elem;
}
return sum;
}
Call the function in a “console.log()” method by passing an array of odd numbers:
After transpile and executing the JavaScript code, the output successfully prints the overall sum of the array of odd numbers:
Example 2: Pass Multi-Type Array
You can also pass the multi-typed array in a function as a parameter. Here, in the given example, we will pass the array with “string” and “number” types to a function. The function iterates over the elements in the array using the “for” loop and prints each element to the console:
for(var i = 0; i < array.length; i++) {
console.log(array[i])
}
}
Now, call the defined function by passing the array that contains string type and number type elements:
Output
That’s all about passing an array in TypeScript.
Conclusion
To pass an array as a parameter in TypeScript, simply declare the parameter as an array type. You can pass any type of array by just specifying the type. Passing an array as a parameter can be a useful way to work with collections of data in TypeScript. This article discussed the procedure to pass an array in TypeScript.