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

To use the invoke function from the Underscore library in TypeScript, first, make sure you have installed the Underscore library and its typing definition:

npm install underscore
npm install --save-dev @types/underscore
64 chars
3 lines

Then, import the Underscore library and use the invoke function as shown below:

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

const myObject = {
  sum: function(a: number, b: number) {
    return a + b;
  }
};

const result = _.invoke([myObject], 'sum', 1, 2);
console.log(result); // Output: [3]
205 chars
11 lines

In the above code, we first import the Underscore library using the import * as _ from 'underscore' statement. Then, we define an object myObject with a sum method that takes two numbers and returns their sum.

Next, we use the _.invoke function to invoke the sum method of myObject by passing [myObject] as the first argument, 'sum' as the second argument, and 1 and 2 as the third and fourth arguments, respectively. _.invoke returns an array of the results of invoking the specified method on each element of the input array. In this case, we have only one element in the input array. Therefore, the output is [3].

Note that we have specified the types of the arguments of the sum method using the number type. This is because we have installed the typing definition of Underscore library using npm install --save-dev @types/underscore command.

gistlibby LogSnag