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

To use the last function from the Underscore library in TypeScript, first, you need to install the Underscore package:

index.ts
npm install underscore
23 chars
2 lines

Then, you can import the last function in your TypeScript file as follows:

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

const nums = [1, 2, 3, 4, 5];
const lastNum = _.last(nums);
console.log(lastNum); // Output: 5
129 chars
6 lines

In this example, we imported the entire Underscore library using the wildcard * and assigned it to the _ variable. Then, we used the last function to get the last element of the nums array and assigned it to lastNum variable. Finally, we logged the lastNum to the console.

Note that if you are using TypeScript 2.9 or later, you can also install the @types/underscore package to get TypeScript typings for the Underscore library:

index.ts
npm install @types/underscore
30 chars
2 lines

This will allow you to use the last function with type safety, like this:

index.ts
import {last} from "underscore";

const nums: number[] = [1, 2, 3, 4, 5];
const lastNum: number | undefined = last(nums);
console.log(lastNum); // Output: 5
157 chars
6 lines

Here, we imported only the last function from the Underscore library using the named import syntax. Then, we used the function with type safety and explicitly specified the type of the nums array as number[]. The last function returns either the last element of the array (in this case, a number) or undefined, so we defined the type of lastNum as number | undefined.

gistlibby LogSnag