Parse const keys to value #936
-
I'm new to zod and am trying to solve a relatively simple problem. I have a const structure, which maps strings to values: const Code = {
'foo': 1,
'bar': 2,
'baz': 3
} as const; I need to define the zod parser for this since the input must be validated against the enumerated keys. For example, the CodeParser.parse({ code: "foo" }) // pass
CodeParser.parse({ code: "something else" }) // fails I tried to define a map like so, but can't really declare it as a const CodeEnum = z.enum(['foo', 'bar', 'baz']);
const CodeMap = z.map(CodeEnum, z.string()); Any pointers appreciated! |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
I think you might be thinking that const Code = { foo: 1, bar: 2, baz: 3 }
type Key = keyof typeof Code
type Keys = [ Key, ...Key[] ]
const codeEnumSchema = z.enum( Object.keys( Code ) as Keys )
.transform( key => Code[ key ] )
type CodeEnumInput = z.input<typeof codeEnumSchema>
// type CodeEnumInput = "foo" | "bar" | "baz"
type CodeEnumOutput = z.output<typeof codeEnumSchema>
// type CodeEnumOutput = number
codeEnumSchema.safeParse( 'foo' ) // { success: true, data: 1 }
codeEnumSchema.safeParse( 'bar' ) // { success: true, data: 2 }
codeEnumSchema.safeParse( 'baz' ) // { success: true, data: 3 }
codeEnumSchema.safeParse( 1 ) // { success: false, error: '...' }
codeEnumSchema.safeParse( 'something else' ) // { success: false, error: '...' } Please let me know if I misunderstood what you are asking. |
Beta Was this translation helpful? Give feedback.
I think you might be thinking that
parse
takes a value and returns another value. Common mistake. But in zod,parse
doesn't do this. You need to define atransform
on your schema to do this. See below.