0

当我遇到障碍时,我正试图在fp-tslocalStorage中编写一个包装器。我想处理值以及抛出的异常,所以我从这段代码开始:nulllocalStorage

import * as IOE from "fp-ts/IOEither";
import * as O from "fp-ts/Option";

const getItem = (key: string): IOE.IOEither<Error, O.Option<string>> =>
  IOE.tryCatch(
    () => O.fromNullable(localStorage.getItem(key)),
    E.toError
  )

上面的函数有一个返回签名IOEither<Error, Option<string>>。我想将 合并Option到 中IOEither,即得到一个IOEither<Error, string>. 我将如何实现这一目标?

PS 我想上述问题在TaskEither<Error, Option<string>>.

4

1 回答 1

2

你可以使用这样的东西:

import * as E from "fp-ts/Either";
import * as IOE from "fp-ts/IOEither";
import * as O from "fp-ts/Option";
import {pipe} from "fp-ts/function";

const getItem = (key: string): IOE.IOEither<Error, string> =>
  pipe(
    IOE.tryCatch(() => O.fromNullable(localStorage.getItem(key)), E.toError),
    IOE.chainEitherK(E.fromOption(() => new Error("key does not exist")))
  );

IOE.chainEitherK(f)相当于IO.map(E.chain(f))

export declare const chainEitherK:
  <E, A, B>(f: (a: A) => Either<E, B>) => (ma: IOEither<E, A>) => IOEither<E, B>

E.fromOption如果选项为 ,则将 anOption<A>转换为Either<E, A>给定的默认错误值None

export declare const fromOption:
  <E>(onNone: Lazy<E>) => <A>(ma: Option<A>) => Either<E, A>
于 2021-05-08T00:46:16.697 回答