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

To use the where function from the Underscore library in TypeScript, you first need to install the @types/underscore package to have the TypeScript typings for Underscore.

You can install the package using npm:

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

Once you have installed the package, you can use the where function from the Underscore library in your TypeScript code as follows:

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

interface Person {
    name: string;
    age: number;
}

const persons: Person[] = [
    { name: "Alice", age: 25 },
    { name: "Bob", age: 30 },
    { name: "Charlie", age: 35 },
];

const filteredPersons = _.where<Person>(persons, { age: 30 });
console.log(filteredPersons);
312 chars
16 lines

In the code above, we first define an interface Person that describes the shape of our objects that we want to filter. We then define an array of Person objects.

We then use the where function from the Underscore library to filter the persons array based on the { age: 30 } criteria. The where function returns an array of objects that match the criteria.

Finally, we log the filtered array to the console.

Note that we use the generic type parameter <Person> with the where function to ensure that the returned array is of the correct type.

gistlibby LogSnag