Trying to extract the type from a key within an array of objects using Zod presents some challenges, especially when the array is nested within another object.
To illustrate the issue:
const obj = z.object({
nestedArray: z.array(z.object({ valueIWant: z.string() }))
})
// Despite attempting to assign the type z.ZodArray(), it still remains as z.ZodObject
const arrayOfObjs = obj.pick({ nestedArray: true })
// Accessing a value in the array using z.ZodArray().element
arrayOfObjs.element.pick({ valueIWant: true })
Expected behavior for arrays in Zod:
// Should be of type z.ZodArray
const arr = z.array(z.object({ valueIWant: z.string() }))
const myValue = arr.element.pick({ valueIWant: true })
The current dilemma involves:
Working with an API that returns the following object structure:
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 specifying tRPC input parameters, I aim to enable filtering by word type. However, manually rewriting
z.enum(['verb', 'adjective', 'noun'])
poses potential issues down the line. How can the word type be inferred through the array?
tRPC endpoint definition:
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
}),
[...]
})