So I'd like to grab the type from a key of an object within an array in Zod. That array is also nested within an object, just to make things extra difficult.
This is an abstract view of the problem I'm having:
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 })
What should happen using arrays in Zod:
// Type of z.ZodArray
const arr = z.array(z.object({ valueIWant: z.string() }))
const myValue = arr.element.pick({ valueIWant: true })
Here is my actual problem:
I have an API which returns the following object:
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'])
})
)
})
In my tRPC input, I would like to allow filtering by word type. Right now, I've had to rewrite z.enum(['verb', 'adjective', 'noun'])
, which isn't great as it could introduce problems later on. How can I infer the type of the word through the array?
tRPC endpoint:
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
}),
[...]
})