mobily / ts-belt

🔧 Fast, modern, and practical utility library for FP in TypeScript.
https://mobily.github.io/ts-belt
MIT License
1.11k stars 31 forks source link

Wrong type definitions for `R.flatMap` and `AR.flatMap` #62

Closed MartinRamm closed 1 year ago

MartinRamm commented 1 year ago

As per documentation, the function given to flatMap is only invoked if the status is Ok. Hence, if the Result was already in an error state BEFORE R.flatMap is invoked, the state doesn't change.

While this is true at runtime, this is not how the type specification is implemented.

For example:

import {R, pipe} from '@mobily/ts-belt';

class Error1 extends Error{}
class Error2 extends Error{}

const value = Math.random() < 0.5 ? null : 'test';
const test = pipe(
  R.fromNullable(value, new Error1()),
  R.flatMap((value) => {
    return Math.random() < 0.5
        ? R.Ok(value)
        : R.Error(new Error2())
    }
  )
)
console.log(test);

The type of test should be Result<string, Error1 | Error2>, but it is Result<string, Error2>.

mobily commented 1 year ago

@MartinRamm thanks for reporting this issue! fixed in v4.0.0-rc.4 🚀 https://github.com/mobily/ts-belt/commit/3e6f0ece9b49ce0dd1ab75858219f86017b3277a

https://github.com/mobily/ts-belt/releases/tag/v4.0.0-rc.4