how to use the foreach function from the underscore library in typescript

To use the forEach() function from the Underscore library in TypeScript, first ensure that Underscore is installed and referenced in your project. Then, import the forEach() function from the Underscore module and use it to iterate over an array as shown in the code example below:

index.ts
import * as _ from 'underscore';

const myArray: number[] = [1, 2, 3, 4, 5];

_.forEach(myArray, (num: number) => {
  console.log(num);
});

// Output:
// 1
// 2
// 3
// 4
// 5
177 chars
15 lines

In this example, we import the Underscore library using the * as _ syntax, which allows us to use the Underscore functions under the _ namespace. Then, we create an array of numbers and use the _.forEach() function to iterate over each element in the array and log it to the console.

Note that we provide a type annotation for the num parameter in the forEach callback function to ensure that TypeScript knows the expected type of the element in the array.

gistlibby LogSnag