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

Assuming that you have already installed the Underscore.js library, you can use the property function to create a function that extracts a property's value from an object. Here's an example in TypeScript:

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

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

// sample data
const people: Person[] = [
  { name: "Alice", age: 30 },
  { name: "Bob", age: 25 }
];

// create a function that extracts the 'name' property
const getName = _.property<Person, string>("name");

// use the function to get an array of names
const names: string[] = _.map(people, getName);

console.log(names); // output: ["Alice", "Bob"]
440 chars
21 lines

In the example above, we import the Underscore.js library and define an interface for a Person object that has name and age properties. We then create an array of Person objects.

Next, we use the property function to create a getName function that extracts the name property from a Person object. We specify the generic type arguments for the property function to let TypeScript know the input and output types of the function.

Finally, we use the getName function with the map function to create an array of names from the original array of Persons. The map function applies the getName function to each element of the people array and returns a new array of just the names.

Note that the property function is a generic function, so you can use it with any type of object and property.

gistlibby LogSnag