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

index.ts
import * as _ from 'underscore';
// or 
import { pick } from 'underscore';

interface Person {
  name: string;
  age: number;
  gender: 'male' | 'female';
}

const person: Person = {
  name: 'John Doe',
  age: 30,
  gender: 'male',
};

const pickedPerson = _.pick(person, 'age', 'gender');
// or
const pickedPerson2 = pick(person, 'age', 'gender');

console.log(pickedPerson);
console.log(pickedPerson2);
405 chars
23 lines

The pick function from the Underscore library in TypeScript allows you to create a new object from an existing one with only the specified properties. It takes the original object as its first argument, followed by one or more property names to include in the new object.

In the above example, we import the pick function from the Underscore library and define an interface for a Person. We then create a person object based on this interface. We then call the pick function twice, once using the full _.pick syntax, and once using the pick import syntax.

The pickedPerson and pickedPerson2 constants both contain a new object that only includes the age and gender properties of the person object. The console output is:

{
  "age": 30,
  "gender": "male"
}
{
  "age": 30,
  "gender": "male"
}
72 chars
9 lines

This demonstrates how to use the pick function from the Underscore library in TypeScript to create a new object with a subset of properties. Remember to import the function, and to specify the original object and desired property names as arguments.

gistlibby LogSnag