对于返回的不同值,我有两个验证函数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的介绍,但该代码与我想要的完全相反:我不关心验证后的输入值,并且只想返回发生的第一个错误。