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.
41 chars2 lines
Once this is done, you can import both the underscore library and the types you need to use the findWhere
function.
index.ts298 chars16 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