Search code examples
typescriptzod

Get schema of an element of the transformed array in `zod`


I have a schema for an object retrieved from back-end. Since the names of the fields in the back-end don't match the naming convention in my front-end, I transform the data and simplify its structure a bit, so I get an array. From this array I can easily infer a type.
In the documentation I see that it should be possible to use .element to access the schema for an element of the array. However, this is not possible and I assume that the reason is that the array is a result of a transformation. If I create an array schema directly, I can do it.

const oZodBackendData = z
  .object({
    results: z.array(
      z.object({
        attr: z.string(),
      })
    ),
  })
  .readonly();

export const oZodData = oZodBackendData 
  .transform((oBackendData) =>
    oBackendData.results.map((oBackendDataElement) => ({
      otherName: oBackendDataElement.attr,
    }))
  )
  .readonly();

export type Data = z.infer<typeof oZodData>;

oZodData.element // Property 'element' does not exist on type ...

Is there an easy solution to this problem?


Solution

  • Zod's transform method doesn't change your original schema. The transform method only chains an additional method onto your validator.

    Because the method doesn't change your original schema to an array validation schema, you don't have access to the element property that Zod's array validation schemas have.