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

如何使用Zod验证字符串字面量类型

用Zod验证TypeScript字符串字面量类型

你可以直接使用Zod的z.enum()方法来匹配你的字符串字面量联合类型,既能完成严格验证,又能让Zod自动推断出和你定义的PaymentType完全一致的类型。

具体实现

把你的字面量值整理成数组传入z.enum()即可,有两种写法可选:

写法1:直接传入字面量数组

import { z } from 'zod';

export type PaymentType = 'CHECK' | 'DIRECT DEPOSIT' | 'MONEY ORDER';

const schema = z.object({
    paymentType: z.enum(['CHECK', 'DIRECT DEPOSIT', 'MONEY ORDER'])
});

写法2:复用枚举值数组(更易维护)

如果后续需要修改枚举值,只改一处即可:

import { z } from 'zod';

// 定义常量数组,用as const确保类型是字面量联合
const paymentTypeValues = ['CHECK', 'DIRECT DEPOSIT', 'MONEY ORDER'] as const;
// 基于数组生成TypeScript类型
export type PaymentType = typeof paymentTypeValues[number];

const schema = z.object({
    paymentType: z.enum(paymentTypeValues)
});

验证效果

  • 传入合法值:schema.parse({ paymentType: 'CHECK' }) 会正常通过
  • 传入非法值:schema.parse({ paymentType: 'CASH' }) 会抛出Zod验证错误,提示值不在允许的枚举列表中

额外技巧:从Zod schema反向生成TypeScript类型

如果不想手动定义PaymentType,可以直接从Zod schema推断类型:

import { z } from 'zod';

const paymentTypeSchema = z.enum(['CHECK', 'DIRECT DEPOSIT', 'MONEY ORDER']);
export type PaymentType = z.infer<typeof paymentTypeSchema>;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 08:05:21