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

To use the propertyOf function from the Underscore library in Typescript, you can follow the steps below:

  1. Install the underscore library by running the following command in your terminal:

    index.ts
    npm install underscore
    
    23 chars
    2 lines
  2. Next, import the propertyOf function from the underscore library in your Typescript file:

    index.ts
    import { propertyOf } from 'underscore';
    
    41 chars
    2 lines
  3. Now, you can create a function that takes an object and a property name as inputs and returns the value of that property from the object using propertyOf:

    index.ts
    function getProperty(obj: any, prop: string) {
      const propValue = propertyOf(obj)(prop);
      return propValue;
    }
    
    112 chars
    5 lines
  4. The getProperty function can now be used to get the value of properties from objects as follows:

    index.ts
    const myObj = { name: 'John', age: 30 };
    const ageValue = getProperty(myObj, 'age'); // Returns 30
    const nameValue = getProperty(myObj, 'name'); // Returns 'John'
    
    163 chars
    4 lines

Note: the any type is used for the obj input parameter in the getProperty function as propertyOf works with any object type. However, it is recommended to use a more specific type for the obj parameter if possible.

gistlibby LogSnag