如何在TypeScript中结合Zod声明BigNumber类型字段?
Zod中如何处理BigNumber类型的解析?
问题场景
我想用Zod替换TypeScript中的interface:
interface args { quantity: number; hugeNum: BigNumber; }
写了如下Zod代码:
const numConstraints = z.number().min(1); const parsedPriceType = z.bigint().optional(); const zArgs = z.object({ quantity: numConstraints, parsedPrice?: parsedPriceType, }); export type myArgs = z.infer<typeof zArgs>;
编译时报错:
Types of property 'parsedPrice' are incompatible. Type 'BigNumber' is not assignable to type 'bigint'.
想知道Zod有没有对应的BigNumber类型,或者怎么实现这个需求?
解决方案
Zod本身没有内置第三方库(比如ethers、bignumber.js)的BigNumber类型,不过可以通过自定义Zod Schema来实现:
1. 自定义BigNumber验证Schema
根据你使用的BigNumber库,编写对应的验证逻辑:
import { z } from "zod"; // 这里以ethers的BigNumber为例,其他库替换对应的导入即可 import { BigNumber } from "ethers"; // 自定义Zod类型,验证输入是否为BigNumber实例,并指定TypeScript类型 const zBigNumber = z.custom<BigNumber>( (value) => value instanceof BigNumber, { message: "输入必须是BigNumber实例" } );
2. 修改Zod对象定义
用自定义的zBigNumber替换原来的z.bigint(),同时注意可选性通过Schema的.optional()实现,不要在对象键名后加?:
const numConstraints = z.number().min(1); // 根据需求决定是否加.optional(),对应原interface中hugeNum的必填/可选 const parsedPriceType = zBigNumber.optional(); const zArgs = z.object({ quantity: numConstraints, parsedPrice: parsedPriceType, }); export type myArgs = z.infer<typeof zArgs>;
这样z.infer<typeof zArgs>得到的myArgs类型中,parsedPrice会是BigNumber | undefined,完全匹配原interface的类型要求。
如果你的BigNumber来自其他库(比如bignumber.js),只需要把验证函数里的instanceof判断换成对应库的BigNumber类即可。
内容的提问来源于stack exchange,提问作者pikovayadama
相关产品推荐
相关产品推荐

