remeda / remeda

A utility library for JavaScript and TypeScript.
http://remedajs.com
MIT License
4.27k stars 130 forks source link

`conditional` type inference broken with `R.conditional.defaultCase()` #770

Open stychu opened 5 days ago

stychu commented 5 days ago

Hi, Im trying to get a grasp of functional programming but having some issues.

How I would pipe a value where it can be an object or undefined and then reference the object propertioes. I cant manage to narrow the correct types.


// value = {    groups: {value: string; initial: string}[]; } | undefined

R.pipe(
          value,
          R.conditional(
           [R.isTruthy, (name) => `Hello ${name}`], // This is unknow
            [R.isObjectType, (name) => `Hello ${name}`], // This is object
            [R.isDefined, (name) => `Hello ${name}`], // this is {}
            R.conditional.defaultCase(),
          ),
        );

Ideally I want an undefined if value is undefined or process the value with some more functions and return it

eranhirsch commented 5 days ago

It might not be something you are doing wrong; there are some known bugs with the typing of conditional, and it isn't working as well as we would want it to be. My recommendation is not to rely on it.

stychu commented 5 days ago

So there is no straight forward way to handle null | undefined values currently?

cjquines commented 4 days ago

this works fine if you pass a function to R.conditional.defaultCase, see playground

i'm surprised it is not a type error to call it without any arguments… i think we should change this?

eranhirsch commented 2 days ago

@cjquines, what is the error? defaultCase without any params would return undefined and is a shorthand to be used when migrating from Lodash where the default fallback returns undefined.

R.conditional.defaultCase() === R.conditional.defaultCase(constant(undefined));
cjquines commented 2 days ago

hm let me clarify. i think type inference is broken when called with () vs when called with (constant(undefined)). i don't know what we can do about this, but i'll keep this issue open for now and clarify the title