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

To use the findWhere function from the underscore library in TypeScript, you need to install @types/underscore as a dev dependency. This will provide TypeScript definitions for the underscore library.

npm install @types/underscore --save-dev
41 chars
2 lines

Once this is done, you can import both the underscore library and the types you need to use the findWhere function.

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

interface User {
    id: number;
    name: string;
}

const users: User[] = [
    { id: 1, name: 'John' },
    { id: 2, name: 'Jane' },
    { id: 3, name: 'Bob' },
];

const user: User = _.findWhere(users, { id: 2 });
console.log(user); // { id: 2, name: 'Jane' }
298 chars
16 lines

In this example, we import underscore using the * as _ syntax, which imports it as a namespace. We also define an interface for the User object so that TypeScript can verify that the objects in the users array have the correct properties.

We then use the findWhere function to search the users array for an object with an id property equal to 2. The resulting user object is logged to the console.

Note that the { id: 2 } argument passed to findWhere is a search criteria object. This can include multiple properties to search for, and underscore will find the first object in the array that matches all of the properties in the search criteria object.

gistlibby LogSnag