能否将Zod Schema用作类型并约束函数仅接受指定Schema?
约束Zod Schema函数参数仅接受特定Schema类型
问题场景
我定义了多个Zod Schema:Schema1、Schema2、Schema3、Schema4和Schema5,需要编写一个函数someFunc,要求它的第二个参数只能传入Schema1和Schema2。当前函数代码如下:
function someFunc(parameter1: any, schema: ???) { schema.parse(.....) // And do something else }
已知将schema参数类型设为z.ZodTypeAny会允许所有Schema传入,想知道有没有办法约束该参数仅接受特定类型的Schema?
解决方案
方法1:直接使用联合类型
直接将参数类型指定为typeof Schema1 | typeof Schema2,TypeScript会自动推导这两个Schema的具体类型,实现精准约束:
import { z } from "zod"; // 示例定义的Zod Schema const Schema1 = z.object({ name: z.string() }); const Schema2 = z.object({ age: z.number() }); const Schema3 = z.object({ email: z.string().email() }); function someFunc(parameter1: any, schema: typeof Schema1 | typeof Schema2) { schema.parse({}); // 执行其他逻辑 } // 合法调用:符合约束条件 someFunc({}, Schema1); someFunc({}, Schema2); // 类型报错:Schema3不在允许范围内 someFunc({}, Schema3);
方法2:定义复用型类型别名
如果需要在多个函数或模块中复用这个约束,可以先定义一个类型别名,再在函数中使用:
import { z } from "zod"; const Schema1 = z.object({ name: z.string() }); const Schema2 = z.object({ age: z.number() }); // 抽取出允许的Schema类型 type AllowedSchema = typeof Schema1 | typeof Schema2; function someFunc(parameter1: any, schema: AllowedSchema) { schema.parse({}); // 执行其他逻辑 }
这两种方式都能精准限制参数只能传入指定的Schema,同时保留Zod Schema的parse等方法的类型提示。
内容的提问来源于stack exchange,提问作者zaplec
相关产品推荐
相关产品推荐

