我正在使用 FP-TS 学习 FP,但遇到了障碍:
我的存储库中有以下功能:
// this is the repository
export const findBook = (id: string) => TaskEither<Error, Option<ParsedBook>>
这部分很简单,对我来说很有意义。问题是当我尝试从我的控制器调用它时:
// this is the controller
export const getBook = (req: unknown) => Task<string | ParsedBook>
无论如何,这是我的getBook
和我正在尝试做的事情:
const getBook: (req: unknown) => T.Task<string | ParsedBook> = flow(
getBookByIdRequestV.decode, // returns Either<Errors, GetBookByIdRequest>
E.fold(
() => T.of('Bad request!'),
flow(
prop('params'),
prop('id'),
findBook, // returns TaskEither<Error, Option<ParsedBook>>
TE.fold(
() => T.of('Internal error.'),
O.fold(
() => T.of('Book not found.'),
(book) => T.of(book) // this line results in an error
)
)
)
)
)
问题是上面的代码给了我一个错误:
Type 'ParsedBook' is not assignable to type 'string'
我认为问题在于E.fold
期望onLeft
和onRight
返回相同类型的结果:
fold<E, A, B>(onLeft: (e: E) => B, onRight: (a: A) => B): (ma: Either<E, A>) => B
但是,它可能不仅返回 a Task<string>
,而且还返回 a Task<ParsedBook>
。
我尝试使用foldW
,它扩大了类型,但同样的错误也是如此。
我真的不知道该怎么办;我觉得我在代码中建模类型的方式很糟糕?
如果有帮助,这里是 Codesandbox:https ://codesandbox.io/s/tender-chandrasekhar-5p2xm?file=/src/index.ts
谢谢!