因此,我想从Zod数组中的对象键中获取类型。该数组也嵌套在一个对象中,这只是为了使事情变得更加困难。
这是我遇到的问题的一个抽象观点:
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输入中,我希望允许按word类型进行过滤。现在,我不得不重写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
}),
[...]
})发布于 2022-07-21 02:30:39
我建议这样做的方法是将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>;同样,我将推荐第一种方法,因为它更可重用,并且不太容易被更新,例如,如果对象改变了形状。
https://stackoverflow.com/questions/73043223
复制相似问题