I commented that this might be a duplicate since the core of the question could be solved with z.literal
, but it is a bit different. Just to illustrate what you can do:
import { z } from 'zod';
const PaymentTypeSchema = z.union([
z.literal('CHECK'),
z.literal('DIRECT DEPOSIT'),
z.literal('MONEY ORDER'),
]);
type PaymentType = z.infer<typeof PaymentTypeSchema>;
const schema = z.object({
paymentType: PaymentTypeSchema,
});
A simpler approach than this is to use the z.enum
helper which removes some of the boilerplate:
const PaymentTypeSchema = z.enum(["CHECK", "DIRECT DEPOSIT", "MONEY ORDER"]);
const schema = z.object({
paymentType: PaymentTypeSchema,
});
Alternatively, you can make PaymentType
into an enum and use z.nativeEnum
to parse the values like:
enum PaymentType {
Check = 'CHECK',
DirectDeposit="DIRECT DEPOSIT",
MoneyOrder="MONEY ORDER"
}
const PaymentTypeSchema = z.nativeEnum(PaymentType);
const schema = z.object({
paymentType: PaymentTypeSchema,
});