Skip to content

Parse const keys to value #936

Answered by JacobWeisenburger
Checksum asked this question in Q&A
Discussion options

You must be logged in to vote

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 a transform on your schema to do this. See below.

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: t…

Replies: 1 comment

Comment options

You must be logged in to vote
0 replies
Answer selected by JacobWeisenburger
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants