Reputation: 782
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.
Upvotes: 1
Views: 764
Reputation: 782
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.
Upvotes: 1
Reputation: 3241
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
Upvotes: 0