zod: z.enum() cannot accept parameter from a json file
What’s the Issue
I have a json file that stores a list of slugs
/* dataSlugs.jsona */
{
"slugs": ["one", "two", "three"]
}
Then I import this json and pass it as parameter toz.enum
import dataSlugs from './dataSlugs.json'
type DataSlugJson = {
slugs: string[]
}
const slugs = (dataSlugs as DataSlugJson).slugs
export const mySchema = z.enum(slugs) /* this throws a type error */
I get the error:
I found in the docs about z.enum can use as const
/* THIS WORKS */
const slugs = ["one", "two" "three"] as const
export const mySchema = z.enum(slugs)
/* BUT THIS DOESN't */
const slugs = (dataSlugs as DataSlugJson).slugs as const
/* ERROR A 'const' assertions can only be applied to references to enum members, or string, number, boolean, array, or object literals.ts(1355) */
export const mySchema = z.enum(slugs)
How can I get a data from a json file, and pass it as parameter to z.enum() ?
ZOD Version
"zod": "^3.21.4"
About this issue
- Original URL
- State: closed
- Created a year ago
- Comments: 22
@NextThread that worked, I guess this is the simplest form:
The Solution
is to use type assertion
as [string]. The docs only mentions the usage ofas constto define the value as tuple. TIL about[string, ...string[]]- I didn’t know you could spread the typestring[].Fix
I guess this is up for the user to cast/assert the type of the value to be passed to
z.enum. Maybe what we can do is to add this assertionas [string]in the z.enum section of the Documentation.sure, just 1 min, I’m on another machine, gimme 1 min