如何使用fp-ts将TaskOption转换为TaskEither完成Schema注册校验
解决方案
你的需求本质是匹配TaskOption的两种状态:
- 返回
Some:Schema已存在,直接返回Left<Error> - 返回
None:Schema未注册,执行保存逻辑返回Right<void>
推荐写法(可读性最高)
直接使用TaskOption.match做分支映射,不需要额外转类型绕路:
import { pipe } from 'fp-ts/function' import * as TO from 'fp-ts/TaskOption' import * as TE from 'fp-ts/TaskEither' const register = (schema: Schema): TE.TaskEither<Error, void> => pipe( find(schema.info), // 你的查询函数,返回TO.TaskOption<Schema> TO.match( // None分支:未找到,执行保存逻辑(保存函数返回TE.TaskEither<Error, void>) () => yourSaveLogic(schema), // Some分支:已找到,返回存在错误 () => TE.left(new Error('Schema已存在')) ) )
你之前写法的问题修正
TE.fromTaskOption 要求必须传入onNone参数,用来指定None状态对应的Left错误值,你省略了该参数所以类型不符合预期。同时TE.fromTaskOption默认分支为None→Left、Some→Right,和你的需求相反,调整后可正常使用:
const register = (schema: Schema): TE.TaskEither<Error, void> => pipe( find(schema.info), // 传入占位值,因为后续要swap分支,None对应的Left会转为Right,无需关心值 TE.fromTaskOption(() => null), TE.swap, // 原Some值现在在Left分支,转为你需要的业务错误 TE.mapLeft(() => new Error('Schema已存在')), // 执行保存逻辑 TE.chain(() => yourSaveLogic(schema)) )
为什么TE.fromTaskOptionK不符合要求
TE.fromTaskOptionK是函数级别的转换工具,作用是把(input: In) => TaskOption<Out>类型的函数整体提升为(input: In) => TaskEither<E, Out>,不是用来处理单个TaskOption值的,所以和你的使用场景不匹配。
内容的提问来源于stack exchange,提问作者Adam A
相关产品推荐
相关产品推荐

