如何在morphic-ts的summoner中注入io-ts-types的自定义编解码器
问题1:是否有可行的实现方式?
有可行的实现方式。
你之前用到的refine方法只适合同类型的值校验,而NumberFromString属于跨类型转换(输入字符串→输出数字),所以不能直接用refine实现,你可以使用F对象内置的custom方法直接封装现有的io-ts编解码器,示例代码如下:
import * as Summoner from '@morphic-ts/batteries/lib/summoner-ESBST'; import { NumberFromString } from 'io-ts-types/lib/NumberFromString'; export interface IAppEnv {} const { summon, tagged } = summonFor<IAppEnv>({}); const ReplyEntry_ = summon((F) => F.interface( { subject: F.string(), action: F.custom(NumberFromString, 'NumberFromString') }, 'ReplyEntry' ) );
如果你需要结合newtype做类型封装,把转换逻辑放在custom传入的编解码器中即可,示例如下:
import { Newtype } from 'newtype-ts'; import { NumberFromString } from 'io-ts-types/lib/NumberFromString'; interface NumberFromStr extends Newtype<{ readonly NumberFromStr: unique symbol }, number> {} const NumberFromStr = summon(F => F.newtype<NumberFromStr>('NumberFromStr')(F.custom(NumberFromString)) );
问题2:是否可以为F对象扩展自定义编解码器?
可以扩展。你可以通过morphic-ts提供的自定义注册能力,把常用的编解码器封装为F的原生方法,避免每次重复编写custom调用,示例如下:
import { defineCustom } from '@morphic-ts/core/lib/hkt'; import { NumberFromString } from 'io-ts-types/lib/NumberFromString'; // 扩展F的类型声明 declare module '@morphic-ts/batteries/lib/summoner-ESBST' { interface SummonerESBSTF { numberFromString: () => ReturnType<typeof defineCustom<typeof NumberFromString>>; } } // 注册自定义方法到summoner const { summon, tagged } = summonFor<IAppEnv>({ custom: { numberFromString: () => defineCustom(NumberFromString) } }); // 后续可直接调用扩展的方法 const ReplyEntry_ = summon((F) => F.interface( { subject: F.string(), action: F.numberFromString() }, 'ReplyEntry' ) );
内容的提问来源于stack exchange,提问作者Dmitrii Bykov
相关产品推荐
相关产品推荐

