Ben Butterworth
Ben Butterworth

Reputation: 28948

How to use drizzle-zod with custom types?

I have a custom type (e.g. citext) but drizzle zod is treating it as unknown:

import { customType } from "drizzle-orm/pg-core";

export const citext = customType<{ data: string }>({
  dataType() {
    return "citext";
  },
});

How can I get drizzle-zod to output the correct type? Example usage:

export const team = pgTable("team", {
  id: text("id").primaryKey(),
  name: citext("name").notNull(),
});

export const selectTeamSchema = createSelectSchema(team);

Unfortunately selectTeamSchema's name property is z.ZodAny, and selectTeamSchema.parse({name: undefined}) doesn't e rror, even though I've used notNull

Upvotes: 1

Views: 1382

Answers (1)

Ben Butterworth
Ben Butterworth

Reputation: 28948

Just override the fields with the second argument.

Simple pattern

export const selectTeamSchema = createSelectSchema(team, {
  name: z.string(),
});

For a more complicated project:

const citextFieldOverrides = {
  name: z.string(),
  // It doesn't let you pass arbitrary properties here (type safe)
} as const;

export const insertTeamSchema = createInsertSchema(team, citextFieldOverrides);
export type InsertMessageSchema = z.infer<typeof insertTeamSchema>;
// add types for citext fields, so that they're not unknown in TS and generated OpenAPI.
export const selectTeamSchema = createSelectSchema(team, citextFieldOverrides);
export type SelectTeamSchema = z.infer<typeof selectTeamSchema>;

Upvotes: 1

Related Questions