0

我试图开始使用 fp-ts,但我遇到了副作用。我编写了一个小测试程序,它将读取一个文件,将文件打印到屏幕上并返回一个 Either<Error, string>。

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

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

此代码可以编译,但 typescript 推断程序变量的类型为 TE.TaskEither<unknown, string>,而我期待的类型为 TE.TaskEither<Error, string>。

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

ps 我使用的是 fp-ts 2.8.6 版

4

1 回答 1

3

您可以使用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)),
);

现在返回TaskEither<Error, string>

您还可以使用以下方法进一步简化它flow

const program = pipe(
  TE.tryCatch(() => readFile(), () => new Error('Failed to read file')),
  TE.chainFirstIOK(flow(log, TE.fromIO)),
);
于 2021-06-16T16:59:19.807 回答