【发布时间】:2019-09-18 20:26:47
【问题描述】:
对于返回Either 的不同值,我有两个验证函数。如果其中一个具有left 值,我想抛出一个异常,如果两者都是right,则什么也不做。我以前从未使用过 fp-ts 并且无法弄清楚如何正确组合左侧结果。我目前的解决方案有效,但感觉我没有正确使用它。
import { Either, left, right, isLeft, getOrElse } from 'fp-ts/lib/Either';
function validateMonth( m: Month ): Either<Error, Month> {
return m.isInRange() ? right(m) : left(new Error('Month must be in range!'));
}
function validateYear( y: Year ): Either<Error, Year> {
return year.isBefore(2038) ? right(y) : left(new Error('Year must be before 2038!'));
}
function throwingValidator(m: Month, y: Year): void {
// todo: Refactor to get rid of intermediate variables,
// combining results of validateMonth and validateYear into a type
// of Either<Error, Unit>
const monthResult = validateMonth( month );
const yearResult = validateYear( year );
const throwOnError = (e: Error) => { throw e; };
if ( isLeft( monthResult ) ) { getOrElse(throwOnError)(monthResult); }
if ( isLeft( yearResult ) ) { getOrElse(throwOnError)(yearResult); }
}
我已阅读https://dev.to/gcanti/getting-started-with-fp-ts-either-vs-validation-5eja 的介绍,但该代码与我想要的完全相反:我不关心验证后的输入值,只想返回发生的第一个错误。
【问题讨论】:
-
getOrElse用于获取结果值,但您没有对它的返回值做任何事情 - 为什么还要调用它?尤其是为什么只在您已经确定它是Left值时才调用它?也就是说,抛出异常在函数式编程中并不是一个真正的好习惯,所以自然有点难。 -
如果不关心返回值,
Either不是返回类型的正确选择。或者至少,不是Either<Error, Result>- 充其量你会做Either<Error, Unit>。 (在 TypeScript 中,Unit是void或undefined或null)。 -
我滥用
getOrElse来调用错误情况的函数。但是您对异常的看法是正确的-我真正想做的是捕获Error对象并将其以被拒绝的承诺返回。当所有值都正确时,我想返回一个具有特定数据结构的 Promise。 -
至少你不应该同时需要
isLeft和getOrElse- 一个就足够了。 -
人们还可以查看这个示例:codesandbox.io/s/…
标签: typescript functional-programming either fp-ts