If I chain through Either in pipe function and if multiple types of lefts are generated, then parameter of Either.mapLeft should show a sum type of all those left types. It returns the type of the first left.
const F = require("fp-ts");
const E = require("fp-ts/lib/Either");
const pipe = F.pipeable.pipe;
class TooBigError extends Error {};
class TooSmallError extends Error {};
pipe(
E.right(2),
E.chain(num => num > 5 ? E.left(new TooBigError()) : E.right(num)),
E.chain(num => num <= 5 ? E.left(new TooSmallError()) : E.right(num)),
// err has the type `TooBigError` (the first `left` above)
// it should have the type `TooBigError | TooSmallError`
E.mapLeft(err => console.log(err.constructor.name))
);
err param in E.mapLeft should have a type of TooBigError | TooSmallError
| Software | Version(s) |
| ---------- | ---------- |
| fp-ts | 2.6.1 |
| TypeScript | 3.8.3 |
You can use chainW to widen the Left type:
import * as E from "fp-ts/lib/Either";
import { pipe } from "fp-ts/lib/pipeable";
class TooBigError extends Error {}
class TooSmallError extends Error {}
pipe(
E.right(2),
E.chain((num: number) =>
num > 5 ? E.left(new TooBigError()) : E.right(num)
),
E.chainW((num: number) =>
num <= 5 ? E.left(new TooSmallError()) : E.right(num)
),
// err has the type `TooBigError | TooSmallError`
E.mapLeft(err => console.log(err.constructor.name))
);
Note that, however, TooBigError and TooSmallError are structurally equivalent, aka the same type for TS: I would consider tracking different errors at type level if possible
@giogonzo is faster than me. I add only a couple of references: see https://github.com/gcanti/fp-ts/issues/1028 and https://github.com/gcanti/fp-ts/issues/904.
Most helpful comment
You can use
chainWto widen theLeft type:Note that, however,
TooBigErrorandTooSmallErrorare structurally equivalent, aka the same type for TS: I would consider tracking different errors at type level if possible