logo
首页
/ 使用Zod处理复杂TypeScript接口的运行时验证

使用Zod处理复杂TypeScript接口的运行时验证

2025-05-03 18:50:00作者:舒璇辛Bertina

在TypeScript项目中,我们经常需要将复杂的接口定义转换为运行时验证方案。Zod作为一个强大的TypeScript-first的验证库,能够很好地解决这个问题。本文将介绍如何使用Zod处理包含联合类型、条件字段和嵌套对象的复杂接口。

复杂接口的挑战

在实际开发中,我们经常会遇到需要处理复杂数据结构的场景。例如,一个金融应用中可能包含多种提现模式,每种模式有不同的字段要求。这些接口通常具有以下特点:

  1. 联合类型:多种可能的类型结构
  2. 条件字段:某些字段的存在依赖于其他字段的值
  3. 嵌套对象:数据结构层级较深
  4. 互斥字段:某些字段不能同时存在

基础类型定义

首先,我们需要定义一些基础类型。在Zod中,可以使用z.literal来创建字面量类型:

const SingleWithdrawModeSchema = z.literal('Single');
const BalancedWithdrawModeSchema = z.literal('Balanced');

对于大整数类型,Zod提供了z.bigint(),但为了更好的兼容性,我们可以扩展支持多种输入格式:

const BigIntSchema = z.union([
  z.bigint(),
  z.number().transform((v) => BigInt(v.toString())),
  z.string().transform((v) => BigInt(v)),
]);

基础接口转换

基础接口BaseWithdraw可以转换为Zod schema:

const BaseWithdrawSchema = z.object({
  pool: AddressSchema,
  burnLpAmount: BigIntSchema,
  queryId: BigIntSchema.optional(),
  recipient: AddressSchema.optional(),
  slippageTolerance: SlippageSchema.optional(),
  extraPayload: z.null().optional(),
});

处理联合类型

对于包含联合类型的接口,如NextWithdraw,我们可以使用z.union

const NextWithdrawSingleSchema = z.object({
  pool: AddressSchema,
  mode: SingleWithdrawModeSchema,
  withdrawAsset: z.union([
    AssetSchema.transform((v) => new Asset(v)), 
    z.instanceof(Asset)
  ]),
});

const NextWithdrawBalancedSchema = z.object({
  mode: BalancedWithdrawModeSchema,
  pool: AddressSchema,
});

const NextWithdrawSchema = z.union([
  NextWithdrawSingleSchema, 
  NextWithdrawBalancedSchema
]);

条件字段处理

对于互斥字段的情况,如SingleWithdrawParams中的withdrawAssetnextWithdraw,我们可以创建两个独立的schema然后合并:

// 第一种情况:有withdrawAsset,无nextWithdraw
const SingleWithdrawNoNextSchema = SingleWithdrawBaseSchema.merge(
  z.object({
    withdrawAsset: z.union([
      z.instanceof(Asset), 
      AssetSchema.transform((v) => new Asset(v))
    ]),
    nextWithdraw: z.undefined(),
  })
);

// 第二种情况:有nextWithdraw,无withdrawAsset
const SingleWithdrawWithNextSchema = SingleWithdrawBaseSchema.merge(
  z.object({
    nextWithdraw: NextWithdrawSchema,
    withdrawAsset: z.undefined(),
  })
).omit({
  withdrawAsset: true,
});

// 合并两种情况
const SingleWithdrawParamsSchema = z.union([
  SingleWithdrawNoNextSchema, 
  SingleWithdrawWithNextSchema
]);

最终schema组合

将所有schema组合成最终的WithdrawParams schema:

const BalancedWithdrawParamsSchema = BaseWithdrawSchema.extend({
  mode: BalancedWithdrawModeSchema,
  nextWithdraw: NextWithdrawSchema.optional(),
});

export const WithdrawParamsSchema = z.union([
  SingleWithdrawParamsSchema, 
  BalancedWithdrawParamsSchema
]);

数据转换处理

为了处理数据序列化,我们可以添加transform方法:

.transform((data) => {
  return {
    ...data,
    toJSON(): Record<string, unknown> {
      const serializeNextWithdraw = (nextWithdraw?: z.infer<typeof NextWithdrawSchema>) => {
        if (!nextWithdraw) return undefined;
        return {
          pool: nextWithdraw.pool.toString(),
          mode: nextWithdraw.mode,
          withdrawAsset: nextWithdraw.mode === 'Single' && nextWithdraw.withdrawAsset
            ? nextWithdraw.withdrawAsset.toJSON()
            : undefined,
        };
      };
      return {
        pool: data.pool.toString(),
        burnLpAmount: data.burnLpAmount.toString(),
        queryId: data.queryId?.toString(),
        recipient: data.recipient?.toString(),
        slippageTolerance: data.slippageTolerance?.toString(),
        extraPayload: data.extraPayload,
        nextWithdraw: serializeNextWithdraw(data.nextWithdraw),
      };
    },
  };
});

类型推断

Zod的一个强大功能是能够从schema推断TypeScript类型:

export type WithdrawParams = z.input<typeof WithdrawParamsSchema>;
export type ParsedWithdrawParams = z.infer<typeof WithdrawParamsSchema>;

总结

通过Zod,我们能够:

  1. 精确地描述复杂的数据结构
  2. 在运行时验证数据是否符合预期
  3. 自动推断TypeScript类型
  4. 处理数据转换和序列化
  5. 实现条件字段和互斥字段的验证

这种方法特别适合需要严格数据验证的场景,如金融应用、API接口等。Zod的类型安全特性能够帮助我们在开发早期发现潜在问题,提高代码质量。

登录后查看全文
热门项目推荐

热门内容推荐

最新内容推荐

项目优选

收起
openGauss-serveropenGauss-server
openGauss kernel ~ openGauss is an open source relational database management system
C++
122
175
RuoYi-Vue3RuoYi-Vue3
🎉 (RuoYi)官方仓库 基于SpringBoot,Spring Security,JWT,Vue3 & Vite、Element Plus 的前后端分离权限管理系统
Vue
823
492
ohos_react_nativeohos_react_native
React Native鸿蒙化仓库
C++
164
255
HarmonyOS-ExamplesHarmonyOS-Examples
本仓将收集和展示仓颉鸿蒙应用示例代码,欢迎大家投稿,在仓颉鸿蒙社区展现你的妙趣设计!
Cangjie
388
366
openHiTLSopenHiTLS
旨在打造算法先进、性能卓越、高效敏捷、安全可靠的密码套件,通过轻量级、可剪裁的软件技术架构满足各行业不同场景的多样化要求,让密码技术应用更简单,同时探索后量子等先进算法创新实践,构建密码前沿技术底座!
C
176
260
MateChatMateChat
前端智能化场景解决方案UI库,轻松构建你的AI应用,我们将持续完善更新,欢迎你的使用与建议。 官网地址:https://matechat.gitcode.com
719
102
Cangjie-ExamplesCangjie-Examples
本仓将收集和展示高质量的仓颉示例代码,欢迎大家投稿,让全世界看到您的妙趣设计,也让更多人通过您的编码理解和喜爱仓颉语言。
Cangjie
323
1.07 K
ShopXO开源商城ShopXO开源商城
🔥🔥🔥ShopXO企业级免费开源商城系统,可视化DIY拖拽装修、包含PC、H5、多端小程序(微信+支付宝+百度+头条&抖音+QQ+快手)、APP、多仓库、多商户、多门店、IM客服、进销存,遵循MIT开源协议发布、基于ThinkPHP8框架研发
JavaScript
89
15
note-gennote-gen
一款跨平台的 Markdown AI 笔记软件,致力于使用 AI 建立记录和写作的桥梁。
TSX
79
2
WxJavaWxJava
微信开发 Java SDK,支持微信支付、开放平台、公众号、视频号、企业微信、小程序等的后端开发,记得关注公众号及时接受版本更新信息,以及加入微信群进行深入讨论
Java
820
22