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: Screenshot 2023-08-04 at 7 52 38 PM

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

Most upvoted comments

@NextThread that worked, I guess this is the simplest form:

import z from 'zod'

import slugs from '../data/slugs.json'

export const slugsSchema = z.enum(slugs.slugs as [string])

The Solution

is to use type assertion as [string]. The docs only mentions the usage of as const to define the value as tuple. TIL about [string, ...string[]] - I didn’t know you could spread the type string[] .

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 assertion as [string] in the z.enum section of the Documentation.

sure, just 1 min, I’m on another machine, gimme 1 min