Types for helper functions for working with schemas? #883
-
I'm trying to write a helper function for wrapping schema parsing in my app, and I'm having some trouble understanding how to handle type definitions. My function is something like function parseInput(input, schema) {
const processedInput = ... // some pre-processing omitted
return schema.safeParse(processedInput);
} I tried a type definition like function parseInput<S extends ZodRawShape, T extends ZodObject<S>>(input: MyInputType, schema: T): ReturnType<T['safeParse']> {
const processedInput = ... // some pre-processing omitted
return schema.safeParse(processedInput);
} (my schema is always an object and I need to access some ZodObject fields during this step), but I get the rather cryptic
Any ideas? |
Beta Was this translation helpful? Give feedback.
Answered by
JacobWeisenburger
Feb 1, 2022
Replies: 1 comment 1 reply
-
I can't figure out why you are getting that error. But if you are wanting to do some preprocessing I would recommend using z.preprocess const schema = z.object( {
foo: z.string(),
bar: z.literal( 'bar' ),
} )
type Schema = z.infer<typeof schema>
// type Schema = {
// foo: string
// bar: "bar"
// }
const preprocessedSchema = z.preprocess( input => {
const processedInput = ... // some pre-processing omitted
return processedInput
}, schema )
type PreprocessedSchema = z.infer<typeof preprocessedSchema>
// type PreprocessedSchema = {
// foo: string
// bar: "bar"
// } |
Beta Was this translation helpful? Give feedback.
1 reply
Answer selected by
msakrejda
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I can't figure out why you are getting that error. But if you are wanting to do some preprocessing I would recommend using z.preprocess