如何使用Zod创建包含静态字段与动态键的Schema?
用Zod实现固定字段+动态键的混合类型
要实现你需要的「既有固定静态字段,又支持任意动态string键(值为string)」的Zod Schema,有两种简洁的可行方式:
方法1:使用catchall(推荐)
Zod的ZodObject提供了catchall方法,可直接为对象中未定义的键设置统一校验规则,完美匹配你的需求:
import { z } from "zod"; const mixedSchema = z.object({ name: z.string(), surname: z.string(), }).catchall(z.string()); // 推导的类型完全符合预期: type MixedType = z.infer<typeof mixedSchema>; // 等价于: // type MixedType = { // [key: string]: string; // name: string; // surname: string; // }
方法2:使用z.intersection
如果需要分开定义固定字段和动态规则,可以用z.intersection将ZodObject和ZodRecord交叉合并:
import { z } from "zod"; const fixedFieldsSchema = z.object({ name: z.string(), surname: z.string(), }); const dynamicFieldsSchema = z.record(z.string()); const mixedSchema = z.intersection(fixedFieldsSchema, dynamicFieldsSchema); // 推导的类型同样满足需求 type MixedType = z.infer<typeof mixedSchema>;
为什么你之前的merge方法报错?
Zod的merge方法仅支持两个ZodObject实例之间的合并,而ZodRecord属于独立的Schema类型(并非ZodObject),因此会抛出类型不兼容的错误,上述两种方法才是正确的合并路径。
内容的提问来源于stack exchange,提问作者DylalyD
相关产品推荐
相关产品推荐

