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

The iteratee function in the Underscore library takes an argument and returns a function that can be used to transform a data set.

Here's an example of how to use the iteratee function in Typescript:

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

// Define an array of objects
const customers = [
  { id: 1, name: 'John', age: 34 },
  { id: 2, name: 'Jane', age: 27 },
  { id: 3, name: 'Sarah', age: 22 }
];

// Define an iterator function using underscore's iteratee
const iterator = _.iteratee<{ age: number }>(function(item) {
  return item.age < 30;
});

// Use the iterator to filter the array of customers
const youngCustomers = _.filter(customers, iterator);

console.log(youngCustomers);
// Output: [ { id: 2, name: 'Jane', age: 27 }, { id: 3, name: 'Sarah', age: 22 } ]
566 chars
20 lines

In this example, we first define an array of objects with the properties id, name, and age. We then define an iterator function using Underscore's iteratee function, which takes an input object and returns a boolean.

The iteratee function is typecasted by using the generic type parameter <{ age: number }> which will infer the shape of the object based on the fields which are used in the iteratee.

Finally, we use the iterator with Underscore's filter function to return an array of all customers whose age is less than 30.

gistlibby LogSnag