[英]Transforming union type into Either type in fp-ts
In typescript, how can I transform a union type A|B
into fp-ts 's Either<A,B>
?在打字稿中,如何将联合类型
A|B
转换为fp-ts的Either<A,B>
? It feels natural and there must be a nice way of doing it.这感觉很自然,必须有一种很好的方法来做到这一点。
I found that it's impossible.我发现这是不可能的。
My original idea was that since union
and Either
type are both sum type, they are algebraically equal.我最初的想法是,由于
union
和Either
类型都是 sum 类型,因此它们在代数上是相等的。 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.问题是,在某一时刻,您必须对具有泛型类型的实例进行类型检查,但根本无法在 Typescript 上执行此操作。
Assuming that you have a type number | string
假设您有一个类型
number | string
number | string
you could do the following: number | string
您可以执行以下操作:
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.但是请记住,
Either
不用于拆分联合类型,而是将错误路径和结果的快乐路径包装在一种类型中。
I have only checked the above code through ts-node.我只通过 ts-node 检查了上面的代码。 I have not seen the actual types generated by TS for the
toEither
function我还没有看到 TS 为
toEither
函数生成的实际类型
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.