zaplec
zaplec

Reputation: 1819

Is it possible to use zod schema as type and constrain it?

I have few Zod schemas. Let's call them Schema1, 2, 3, 4 and 5. I am trying to create a function that should allow only schemas 1 and 2 as its second parameter

function someFunc(parameter1: any, schema: ???) {
  schema.parse(.....)
  // And do something else
}

I know I could type the schema in the function as z.ZodTypeAny, but then that would allow all the schemas to be passed into the function. Is there a way to constrain the schema parameter so that it would only allow certain type of schemas passed into the function?

Upvotes: 2

Views: 3154

Answers (1)

Romain TAILLANDIER
Romain TAILLANDIER

Reputation: 1995

As suggested in comments, that could be the trick for you.

function someFunc(parameter1: any, schema: typeof schema1 | typeof schema2) {...}

You can also (I suppose) create a dedicated type :

type typeForSomeFunc = typeof schema1 | typeof schema2;
function someFunc(parameter1: any, schema: typeForSomeFunc) {...}

Upvotes: 1

Related Questions