Say you have a basic system like this in Zod:
import { z } from 'zod'
const Post = z.object({
title: z.string(),
})
const User = z.object({
name: z.string(),
email: z.string().optional(),
posts: z.array(Post),
loginCount: z.number().min(1)
})
How do you iterate through the properties and inspect the options on the properties?
I see there is a .shape
property, but how do you do this:
for (const name in shape) {
const prop = shape[name]
if (prop.min != null) {
console.log(`Has min ${prop.min}`)
}
if (prop.max != null) {
console.log(`Has max ${prop.max}`);
}
if (prop.optional === true) {
console.log(`Is optional`);
}
if (prop.type) {
if (prop.type is array) {
prop.type.forEach(item => {
console.log(`Has array item type ${item.name}`)
})
} else if (prop.type is union) {
// ... show union type names
} else {
// show basic type name
}
}
}
I need to use this definition to, for example:
- Get the keys of each schema
- Get the allowed property type(s) for a property on a schema (so I can know what db table to insert into, for example)
- Make documentation
- Stuff like that.
I don't see any docs for stuff like this and don't want to end up reinventing the wheel by making my own library to do types and type inspection.