gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 02:27:41 24 4
gpt4 key购买 nike

所以我想从 Zod 中的数组中的对象的键中获取类型。该数组还嵌套在一个对象中,只是为了让事情变得更加困难。

这是我遇到的问题的抽象 View :

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 中使用数组会发生什么:

// Type of z.ZodArray
const arr = z.array(z.object({ valueIWant: z.string() }))

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

这是我的实际问题:

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

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 输入中,我希望允许按词类型进行过滤。现在,我不得不重写 z.enum(['verb', 'adjective', 'noun']),这不是很好,因为它可能会在以后引入问题。如何通过数组推断单词的类型?

tRPC 端点:

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
}),
[...]
})

最佳答案

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

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 类型。

但是,可以像这样从嵌套对象中提取类型:

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

同样,我会推荐第一种方法,因为它的可重用性更高,并且在对象改变形状等情况下不易需要更新。

关于arrays - 从数组 Zod 中对象的键推断类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73043223/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com