Search code examples
typescriptruntimezod

Creating zod schema for generic interface


I've got this generic interface for paginated response:

export interface PaginatedResponse<T> {
  pageIndex: number;
  pageSize: number;
  totalCount: number;
  totalPages: number;
  items: Array<T>;
}

And then I want to turn it in zod schema for runtime type checks. The approach was like this:

const PaginatedResponseSchema = z.object({
  pageIndex: z.number(),
  pageSize: z.number(),
  totalCount: z.number(),
  totalPages: z.number(),
  items: z.array(???), // <=
});

export type PaginatedResponse<T> = z.infer<typeof PaginatedResponseSchema>;

What type of array should be items in the schema?


Solution

  • You can create a generic function that returns a new schema given a schema for the items field. So for example you could write:

    function createPaginatedResponseSchema<ItemType extends z.ZodTypeAny>(
      itemSchema: ItemType,
    ) {
      return z.object({
        pageIndex: z.number(),
        pageSize: z.number(),
        totalCount: z.number(),
        totalPages: z.number(),
        items: z.array(itemSchema),
      });
    }
    

    This section in the zod docs goes into more specifics about generic functions.