有没有办法将 IO 投射到 TaskEither

Is there a way to cast an IO to TaskEither

我正尝试开始使用 fp-ts,但我在副作用方面遇到了很大困难。 我写了一个小测试程序,它将读取一个文件,将文件打印到屏幕上,然后 return 一个 Either.

我以基本的 do notation 为例,最后得到了一个看起来像这样的代码

const program = pipe(
    TE.tryCatch(() => readFile(), () => new Error('Failed to read file')),
    TE.chainFirst((text) => pipe(log(text), TE.fromIO)),
);

此代码可以编译,但 typescript 推断程序变量的类型为 TE.TaskEither 而我期望的类型为 TE.TaskEither

有没有办法将错误类型保留在 TaskEither 中?还是我用错了这个库?

p.s 我正在使用 fp-ts 版本 2.8.6

您可以使用 chainFirstIOK:

export declare const chainFirstIOK: <A, B>(f: (a: A) => IO<B>) => <E>(first: TaskEither<E, A>) => TaskEither<E, A>
const program = pipe(
    TE.tryCatch(() => readFile(), () => new Error('Failed to read file')),
    TE.chainFirstIOK((text) => pipe(log(text), TE.fromIO)),
);

现在returnsTaskEither<Error, string>.

您还可以使用 flow:

进一步简化它
const program = pipe(
  TE.tryCatch(() => readFile(), () => new Error('Failed to read file')),
  TE.chainFirstIOK(flow(log, TE.fromIO)),
);