switching to lodash/fp from lodash causes typescript errors

Viewed 622

I have this line

return _.uniqBy(arr1.concat(arr2), 'id');

that works fine when I use regular lodash

but when I try and switch the import to lodash/fp I get this error

TS2769: No overload matches this call.
Overload 1 of 3, '(iteratee: LoDashStatic, array: List<string> | null | undefined): LodashUniqBy1x2<string>', gave the following error. 

Argument of type 'Entity[]' is not assignable to parameter of type 'LoDashStatic'.

Overload 2 of 3, '(iteratee: ValueIteratee<string>, array: List<string> | null | undefined): string[]', gave the following error.     
Argument of type 'Entity[]' is not assignable to parameter of type 'ValueIteratee<string>'.       

Type 'Entity[]' is not assignable to type '[string | number | symbol, any]'.

My import looks like this import * as _ from 'lodash/fp', changed from import * as _ from 'lodash

There seems to be multiple errors like this, but haven't seen any complaints online. Is there something i'm doing wrong when trying to convert?

2 Answers

Lodash/fp is a functional version of Lodash. It plays very well with things like function composition etc...

The "trick" to thinking about using these Lodash/fp functions is to remove the thing that you're doing the work to. Only think about the work that needs to be done.

Example...

Lets say you have an array of users who each have an age and you want to find the oldest one.

With Lodash you might do something like...

const oldestUserName = (users: any[]) => {
    const oldestUser = _.maxBy(users, 'age')
    return _.get(oldestUser, 'name')
};

In this code we are very explicitly doing work to the users array. Getting an object out of the array. And then diving into that object to get the name out.

With lodash/fp you don't need to be dealing with these objects. Only the work that needs doing.

const oldestUserNameFP = _.flow(
    _.maxBy('age'),
    _.get('name')
);

You have now created a function that composes together several functions (flow is an essential part of FP and really worth learning about).

I can now run...

console.log("Hello: ", oldestUserNameFP(users))

And it will first get the max user by age and then get their name.

This is a very trivial example but the more you use it the more you will see how powerful it is.

I've built a JSON parser that takes in 1 of 20 different JSON formats that come from a webhook and transforms them into a format that the app we're working on can accept.

The entire parser is essentially a single FP function that will route the JSON through and parse out the individual properties etc...

The type signature for lodash and lodash/fp is different. Change from this:

_.uniqBy(arr1.concat(arr2), 'id')

to this:

_.uniqBy('id', arr1.concat(arr2))
Related