[英]Transforming union type into Either type in fp-ts
在打字稿中,如何将联合类型A|B
转换为fp-ts的Either<A,B>
? 这感觉很自然,必须有一种很好的方法来做到这一点。
我发现这是不可能的。
我最初的想法是,由于union
和Either
类型都是 sum 类型,因此它们在代数上是相等的。 因此,必须有一种自然而美好的方式来相互转化。
问题是,在某一时刻,您必须对具有泛型类型的实例进行类型检查,但根本无法在 Typescript 上执行此操作。
假设您有一个类型number | string
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
),
)
这将产生:
toEither(4)
{ _tag: 'Left', left: 4 }
toEither('Foo')
{ _tag: 'Right', right: 'Foo' }
但是请记住, Either
不用于拆分联合类型,而是将错误路径和结果的快乐路径包装在一种类型中。
我只通过 ts-node 检查了上面的代码。 我还没有看到 TS 为toEither
函数生成的实际类型
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.