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

To use the findKey function from the Underscore library in TypeScript, first install the library through NPM:

npm install underscore
23 chars
2 lines

Then, import the findKey function:

index.ts
import { findKey } from 'underscore';
38 chars
2 lines

The findKey function takes two arguments: an object and a predicate function. The predicate function is called for each key-value pair in the object, with the value as the first argument and the key as the second argument. If the predicate function returns a truthy value, findKey returns the corresponding key. If the predicate function returns falsey for all key-value pairs, findKey returns undefined.

Here's an example usage of findKey:

index.ts
interface Person {
  name: string;
  age: number;
}

const people: Record<string, Person> = {
  'person1': { name: 'Alice', age: 25 },
  'person2': { name: 'Bob', age: 30 },
  'person3': { name: 'Charlie', age: 35 },
};

const keyForAlice = findKey(people, person => person.name === 'Alice');
// keyForAlice === 'person1'
322 chars
14 lines

gistlibby LogSnag