1

In typescript, how can I transform a union type A|B into fp-ts's Either<A,B>? It feels natural and there must be a nice way of doing it.

Ingun전인건
  • 672
  • 7
  • 12

2 Answers2

1

I found that it’s impossible.

My original idea was that since union and Either type are both sum type, they are algebraically equal. Therefore there must be a natural and nice way of transforming to each other.

The problem was that at one point you have to typecheck an instance with a generic type but there’s simply no way of doing it on Typescript.

Ingun전인건
  • 672
  • 7
  • 12
0

Assuming that you have a type number | string you could do the following:

import * as E from 'fp-ts/lib/Either'
import * as F from 'fp-ts/lib/function'

const toEither = F.flow(
    E.fromPredicate(
        x => typeof x === 'string', // Assuming that string is the Right part
        F.identity
    ),
)

Which will produce:

toEither(4) 
{ _tag: 'Left', left: 4 }
toEither('Foo')
{ _tag: 'Right', right: 'Foo' }

BUT Keep in mind that Either is not used to split union types but to wrap the error path and your happy path of your result in one type.

I have only checked the above code through ts-node. I have not seen the actual types generated by TS for the toEither function

antoniom
  • 3,143
  • 1
  • 37
  • 53
  • 1
    `Either` is just a bifunctor where `map` ops on the right side and `mapLeft` operates on the left side. Its usage is not just for handling "happy" and errors. It can be used to split union types just fine so long as you remember that `map` and `mapLeft` will only operate on one of the two sides each. From Haskell's page on `Either`: `The Either type represents values with two possibilities: a value of type Either a b is either Left a or Right b. The Either type is sometimes used to represent a value which is either correct or an error` That's why it's called `Either` and not Success` – user1713450 Oct 16 '20 at 15:15