colinhacks / zod

TypeScript-first schema validation with static type inference
https://zod.dev
MIT License
33.09k stars 1.15k forks source link

Infer new schema from parsed output #3668

Open nimonian opened 1 month ago

nimonian commented 1 month ago

I have a schema something like this:

UserPost = z.object({
  username: z.string(),
  password: z.string().min(8).transform(val => hash(val))
})

What I'd like to do is create a new schema based on the output of UserPost.parse().

Something like this:

UserRecord = UserPost.output()

so that when I read the data again at a later time, I can parse it to be confident that it has not been corrupted.

I am aware that a type can be inferred this way:

type output = z.output<typeof UserPost>

But is it possible to infer a new Zod schema in a similar way?

(This is just an example by the way, it doesn't really represent my auth strategy!)