Creating a zod enum from an object

clock icon

asked 3 months ago Asked

message

3 Answers

eye

25 Views

 

I have this object:

const properties = [
  { value: "entire_place", label: "The entire place" },
  { value: "private_room", label: "A private room" },
  { value: "shared_room", label: "A shared room" },
] as const;

I need to use it with zod in order to

  1. Validate and parse my data on the backend
  2. Create a typescript union type with those possible values "entire_place" | "shared_room" | "private_room"

According to the zod documentation, i can do this:

const properties = [
  { value: "entire_place", label: "The entire place" },
  { value: "private_room", label: "A private room" },
  { value: "shared_room", label: "A shared room" },
] as const;

const VALUES = ["entire_place", "private_room", "shared_room"] as const;
const Property = z.enum(VALUES);
type Property = z.infer<typeof Property>;

However, I don't want to define my data twiceone time with a label (the label is used for ui purposes), and another without a label.

I want to define it only once using the properties object, without the VALUES array, and use it to create a zod object and infer the type from the zod object.

Any solutions how?

3 Answers

In this case, I think I would infer the type for Property from properties directly. You can avoid repeating yourself with code like:

import { z } from "zod";

const properties = [
  { value: "entire_place", label: "The entire place" },
  { value: "private_room", label: "A private room" },
  { value: "shared_room", label: "A shared room" }
] as const;

type Property = typeof properties[number]["value"];
// z.enum expects a non-empty array so to work around that
// we pull the first value out explicitly
const VALUES: [Property, ...Property[]] = [
  properties[0].value,
  // And then merge in the remaining values from `properties`
  ...properties.slice(1).map((p) => p.value)
];
const Property = z.enum(VALUES);

I took the example of the @SprinkleDev above and created a simplified version

import { z } from 'zod'
function z_enumFromArray(array: string[]){
  return z.enum([array[0], ...array.slice(1)])
}


// example of user19910212
const properties = [
  { value: "entire_place", label: "The entire place" },
  { value: "private_room", label: "A private room" },
  { value: "shared_room", label: "A shared room" },
] as const;
const propertySchema = z_enumFromArray(properties.map(prop=>prop.value))
propertySchema.parse("entire_place") // pass
propertySchema.parse("invalid_value") // throws error


// Another example using an Object as input
const status = {
  active: "B0A47BD3-5CC2-49EF-BA69-9BC881A2B6C2",
  inactive: "BDABF381-FA76-4578-81EC-FF3E56055A9E",
  pending: "2B517D1B-1710-41A6-B946-7AE2B93C7DDE",
} as const
const statusSchema = z_enumFromArray(Object.keys(status))
statusSchema.parse("active") // pass
statusSchema.parse("invalid_value") // throws error

Write your answer here

Top Questions