You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改Zod输出类型?以Flavor类型UserId为例

问题:让Zod Schema输出Flavor类型而非原始类型

我们通过Flavor类型定义了UserId:

interface Flavoring<FlavorT> {
  _type?: FlavorT;
}
type Flavor<T, FlavorT> = T & Flavoring<FlavorT>;

type UserId = Flavor<string, 'UserId'>;

我们希望Zod Schema推断出的类型是UserId,而非普通的string。目前使用refine方法可以实现这一效果,但想找到无需额外函数调用的更优方案:

const MySchema = z.object({
  id: z.string().refine((v): v is UserId => true),
});

type MySchemaType = z.infer<typeof MySchema>;

// 推断结果:
// type MySchemaType = {
//    id: string & Flavoring<"UserId">;
// }

内容的提问来源于stack exchange,提问作者TmTron

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 09:34:52