zod icon indicating copy to clipboard operation
zod copied to clipboard

Feature Request: Runtime introspection of the output type of a zod schema

Open GrantJamesPowell opened this issue 10 months ago • 0 comments

Hi!

Absolutely love zod, it's the first package I add to any TS project I'm working on.

I'm curious if zod has support / docs / examples of other projects that read schema types at runtime? Is depending on the internals of zod to do this a bad idea?

I'm the maintainer of the ERA relational algebra library. It ships with a runtime relational algebra type checker for type checking queries. I'd like to build a feature in ERA that roughly looks like this

class Relation {
  /* .. */
   
  compile<T extends z.ZodTypeAny>(zodSchema: T): () => Promise<z.infer<T>[]> {
      // at runtime, the relation class runs ERA typechecker and knows the type of the 
      // output of this sql query. Lets say the query returns rows of the form `{ foo: string | null, bar: number }`
      // I'd like to use `zodSchema` at runtime and make sure it can accept values of that form before
      // actually running the query.
      
      // Conceptual pseudo code
     for (const zodField of zodSchema.something) {
        assert(compatible(zodField, eraTypeCheck[zodField.name]))
     } 
  }
} 

Another way this could be accomplished is generating a zod schema from the era types and some sort of z.implementsOutputOf

schemaA.implementsOutputOf(schemaB)

GrantJamesPowell avatar Apr 18 '24 14:04 GrantJamesPowell