how to use the invert function from the lodash library in typescript

To use the invert function from the Lodash library in TypeScript, first install the Lodash library:

index.ts
npm install lodash
19 chars
2 lines

Then, import the function and use it as follows:

index.ts
import { invert } from 'lodash';

interface MyObject {
  [key: string]: string | number;
}

const myObject: MyObject = { a: 1, b: '2', c: 3 };
const invertedObject = invert(myObject);
console.log(invertedObject);
213 chars
10 lines

By default, the invert function expects an object with string values. However, you can use a type definition to support objects with keys of a specific type. In this example, we use an interface MyObject with a string key and either a string or number value.

Note that the invert function creates a new object with the keys and values swapped, so the resulting object has the previous values as keys and the previous keys as values.

gistlibby LogSnag