首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从数组Zod中的对象键推断类型

从数组Zod中的对象键推断类型
EN

Stack Overflow用户
提问于 2022-07-19 20:37:16
回答 1查看 2.2K关注 0票数 3

因此,我想从Zod数组中的对象键中获取类型。该数组也嵌套在一个对象中,这只是为了使事情变得更加困难。

这是我遇到的问题的一个抽象观点:

代码语言:javascript
复制
const obj = z.object({
  nestedArray: z.array(z.object({ valueIWant: z.string() }))
})

// Should be of type z.ZodArray() now, but still is of type z.ZodObject
const arrayOfObjs = obj.pick({ nestedArray: true })

// Grab value in array through z.ZodArray().element
arrayOfObjs.element.pick({ valueIWant: true })

在Zod中使用数组应该发生什么:

代码语言:javascript
复制
// Type of z.ZodArray
const arr = z.array(z.object({ valueIWant: z.string() }))

const myValue = arr.element.pick({ valueIWant: true })

这是我的实际问题:

我有一个API,它返回以下对象:

代码语言:javascript
复制
export const wordAPI = z.object({
  words: z.array(
    z.object({
      id: z.string(),
      word: z.string(),
      translation: z.string(),
      type: z.enum(['verb', 'adjective', 'noun'])
    })
  )
})

在我的tRPC输入中,我希望允许按word类型进行过滤。现在,我不得不重写z.enum(['verb', 'adjective', 'noun']),这并不好,因为它以后可能会带来问题。如何通过数组推断单词的类型?

tRPC端点:

代码语言:javascript
复制
export const translationsRouter = createRouter().query('get', {
  input: z.object({
    limit: z.number().default(10),
    avoid: z.array(z.string()).nullish(),
    wordType: z.enum(['verb', 'adjective', 'noun']).nullish() // <-- infer here
  }),
  [...]
})
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-07-21 02:30:39

我建议这样做的方法是将wordType字段提取为一个单独的模式,然后在z.object中使用该模式。比如:

代码语言:javascript
复制
const wordTypeSchema = z.enum(["verb", "adjective", "noun"]);
type WordType = z.TypeOf<typeof wordTypeSchema>;
export const wordAPI = z.object({
  words: z.array(
    z.object({
      id: z.string(),
      word: z.string(),
      translation: z.string(),
      type: wordTypeSchema
    })
  )
});

然后,我将只使用WordType类型,在其他需要的地方,只需要这个值。

但是,从嵌套对象中提取类型是可能的,如下所示:

代码语言:javascript
复制
type WordAPI = z.TypeOf<typeof wordAPI>;
type WordType = WordAPI['words'][number]['type'];
//    ^- This will include `| null` because you used `.nullable`
// If you don't want the | null you would need to say
type WordTypeNotNull = Exclude<WordType, null>;

同样,我将推荐第一种方法,因为它更可重用,并且不太容易被更新,例如,如果对象改变了形状。

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73043223

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档