Fixing TypeScript Errors with Prisma `createMany` and Zod Inference
Resolve TypeScript errors caused by mismatched input types in Prisma's `createMany` method using a reusable utility to infer types directly from the Prisma Client.
Resolve TypeScript errors caused by mismatched input types in Prisma's `createMany` method using a reusable utility to infer types directly from the Prisma Client.
createMany
and Zod InferenceWhen working with Prisma and Zod in a TypeScript project, you might run into a frustrating error like this:
Type '{ ... }[]' is not assignable to type 'AttachmentCreateManyInput[]'.
Property 'url' is optional in type '{ ... }' but required in type 'AttachmentCreateManyInput'.
This happens even when your Zod schema defines all required fields correctly.
Prisma’s createMany method expects a very specific type for the data field (e.g. AttachmentCreateManyInput[]), but Prisma doesn’t export that type for direct use. Even if your Zod schema validates everything, TypeScript won’t automatically know that your inferred types are 100% compatible with Prisma’s expectations.
To bridge the gap, we can extract the correct type using TypeScript’s infer keyword and Prisma’s delegate methods.
import { PrismaClient } from '@prisma/client';
const prisma = new PrismaClient();
type PrismaModelName = keyof PrismaClient;
type GetDelegate<Model extends PrismaModelName> = NonNullable<PrismaClient[Model]>;
type InferCreateManyInput<Model extends PrismaModelName> =
GetDelegate<Model> extends { createMany: (...args: infer Args) => any }
? Args[0] extends { data: infer D }
? D
: never
: never;
type AttachmentCreateManyInput = InferCreateManyInput<'attachment'>;
await prisma.attachment.createMany({
data: input.data as AttachmentCreateManyInput,
skipDuplicates: true,
});
By using this utility, you can ensure that your Zod-validated input conforms to what Prisma expects — and TypeScript will no longer complain.
This pattern works across any model in your Prisma schema and avoids maintaining separate, duplicate types. You can even extend it to create similar helpers for create, update, or deleteMany inputs.