如何迭代属性并获取 Zod 中的类型?

问题描述 投票:0回答:0

假设您在 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)
})

如何遍历属性并检查属性的选项?

我看到有一个

.shape
属性,但是你是怎么做到的:

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
    }
  }
}

我需要使用这个定义,例如:

  • 获取每个schema的key
  • 获取模式属性的允许属性类型(例如,这样我就可以知道要插入哪个数据库表)
  • 制作文档
  • 那样的东西。

我没有看到任何此类内容的文档,也不想通过创建自己的库来进行类型和类型检查来重新发明轮子。

typescript zod
© www.soinside.com 2019 - 2024. All rights reserved.