【问题标题】:How to convert Either<Error, Task<any>> into TaskEither<Error, any> in fp-ts如何在 fp-ts 中将 Either<Error, Task<any>> 转换为 TaskEither<Error, any>
【发布时间】:2020-01-02 13:19:18
【问题描述】:

我有一个返回 Either&lt;Error, Task&lt;any&gt;&gt; 的管道,但我需要的是 TaskEither&lt;Error, any&gt;

如何将Either&lt;Error, Task&lt;any&gt;&gt; 转换为TaskEither&lt;Error, any&gt;

是否有任何辅助功能可以做到这一点?

【问题讨论】:

    标签: typescript functional-programming fp-ts


    【解决方案1】:

    解决办法在这里:

    https://github.com/gcanti/fp-ts/issues/1072#issuecomment-570207924

    declare const a: E.Either<Error, T.Task<unknown>>;
    
    const b: TE.TaskEither<Error, unknown> = E.either.sequence(T.task)(a);
    

    【讨论】:

      【解决方案2】:

      您可以创建以下转换:

      import { Either } from "fp-ts/lib/Either";
      import { Task } from "fp-ts/lib/Task";
      import { fromEither, rightTask, chain } from "fp-ts/lib/TaskEither";
      import { pipe } from "fp-ts/lib/pipeable";
      
      type MyType = { a: string }; // concrete type instead of any for illustration here
      
      declare const t: Either<Error, Task<MyType>>; // your Either flying around somewhere
      
      const result = pipe(
        fromEither(t), // returns TaskEither<Error, Task<MyType>>
        chain(a => rightTask(a)) // rightTask returns TaskEither<Error, MyType>, chain flattens
      ); 
      
      // result: TaskEither<Error, MyType>
      

      PS:我本来想写chain(rightTask),但Error 类型不能用这个速记正确推断(现在完全确定原因)。

      尽管如此,对于这些强大的类型来说,这是一个便宜的价格,并且可以提供您想要的结果!

      【讨论】:

        猜你喜欢
        • 2018-06-23
        • 2020-08-16
        • 2020-06-18
        • 1970-01-01
        • 2021-07-17
        • 1970-01-01
        • 2018-12-02
        • 2019-06-08
        • 1970-01-01
        相关资源
        最近更新 更多