5

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?

ligowsky
  • 1,953
  • 4
  • 13
  • 15

1 Answers1

7

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.

Souperman
  • 5,057
  • 1
  • 14
  • 39