Typescript

How Can I Pass an Array in TypeScript?

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:

function func (array: type[]){
// 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:

function sum(array: number[]) {
 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:

console.log(sum([1, 3, 5, 7, 9, 11, 15]));

 
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:

function printArrayElements(array: (string | number)[]) {
 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:

console.log(printArrayElements(['red', 1, 5, 7, 'blue', 'purple', 9, 11]);

 
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.

About the author

Farah Batool

I completed my master's degree in computer science. I am an academic researcher and love to learn and write about new technologies. I am passionate about writing and sharing my experience with the world.