In the React 18 for Beginners course, the sample Expense Form uses Zod to generate the schema. For the category field in the schema, the sample uses Zod enum as follows:
category: z.enum(categories),
The issue is that the categories array must be defined as a const array suffixed with “as const” for this to work:
export const categories = [“Entertainment”, “Groceries”, “Utilities”] as const;
Although this works, what if you want to allow the user to add a new category? This is a typical real world scenario. How do you work around this issue? I want to avoid “as const” so new categories can be added later but still use the array with the Zod enum type. I have found no way to copy the array (without “as const”) to another “as const” array to get around this issue as follows:
// as const not used to allow adding other items to this array:
export const categories = [“Entertainment”, “Groceries”, “Utilities”]
// Attempt to copy to an “as const” array for use by Zod enum:
const constCategories = […categories] as const;
The above would be followed by using constCategories instead of categories with Zod enum:
category: z.enum(constCategories),
But this still results in the same type error if you simply didn’t use “as const” on the original array. I.e., export const categories = [“Entertainment”, “Groceries”, “Utilities”]