colinhacks / zod

TypeScript-first schema validation with static type inference
https://zod.dev
MIT License
33.09k stars 1.15k forks source link

Add Optional Descriptions to Enums in Zod for Enhanced Schema Clarity #3734

Open tito-arch opened 2 weeks ago

tito-arch commented 2 weeks ago

Enums are widely used to represent a fixed set of values but cannot currently carry additional metadata such as descriptions. Adding optional descriptions would make schemas more informative and easier to understand, especially in complex applications where context is key.


import { z } from "zod";

// Current approach without descriptions
export const ProductCategorySchema = z.enum(["electronics", "clothing", "furniture"]);

// Descriptions would be managed separately
const categoryDescriptions = {
    electronics: "Devices and gadgets such as smartphones, laptops, and cameras.",
    clothing: "Apparel including shirts, pants, dresses, and accessories.",
    furniture: "Home and office furnishings like chairs, tables, and sofas."
};

// Usage example
const selectedCategory = "electronics";
const description = categoryDescriptions[selectedCategory] || "No description available";
console.log(`Category: ${selectedCategory}`);
console.log(`Description: ${description}`);

Proposed Implementation

Extend Zod’s Enum Schema: Add optional description support directly within Zod’s enum definitions, allowing for cleaner and more integrated schema management.

import { z } from "zod";

// Define a schema with optional descriptions
export const ProductCategorySchema = z.enum([
    { value: "electronics", description: "Devices and gadgets such as smartphones, laptops, and cameras." },
    { value: "clothing", description: "Apparel including shirts, pants, dresses, and accessories." },
    { value: "furniture", description: "Home and office furnishings like chairs, tables, and sofas." }
]);

// Accessing descriptions directly
const category = ProductCategorySchema.enumValues.find(v => v.value === "electronics");
console.log(`Category: ${category.value}`);
console.log(`Description: ${category.description}`);

Backward Compatibility Non-Disruptive Change: This feature introduces descriptions as an optional addition to enums. Existing code using enums without descriptions will remain unaffected. Optional Descriptions: The feature will be available but not required, allowing developers to adopt it at their own pace.