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

To use the get function from the underscore library in TypeScript, first install the @types/underscore package using npm:

npm install --save-dev @types/underscore
41 chars
2 lines

Once installed, you can import the get function from the underscore module and use it in your TypeScript code as follows:

index.ts
import { get } from 'underscore';

interface Example {
  nestedObj?: {
    property: string;
  };
}

const example: Example = { nestedObj: { property: 'example' } };

const propertyValue = get(example, 'nestedObj.property');
console.log(propertyValue); // Output: 'example'
274 chars
13 lines

Alternatively, if you want to use the get function from underscore without installing the types for it, you can declare the function signature yourself using generics like this:

index.ts
declare function get<T, K extends keyof T>(obj: T, key: K): T[K];
66 chars
2 lines

With this declaration, you can use the get function in your TypeScript code just like in the previous example. However, note that you won't get any type checking or auto-completion for the get function arguments and return value without installing the correct types.

gistlibby LogSnag