Fixing TypeScript Errors with Prisma `createMany` and Zod Inference

Stephen Burke

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.

🛠️ Fixing TypeScript Errors with Prisma createMany and Zod Inference

When 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.

🧠 Why This Happens

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.

✅ The Solution: Infer the Type from Prisma Client Itself

To bridge the gap, we can extract the correct type using TypeScript’s infer keyword and Prisma’s delegate methods.

🔧 Reusable Utility Type

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;

✅ Usage Example

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.

🧼 Clean, Type-Safe, and Reusable

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.


Thank you for reading! If you enjoyed this post, feel free to share it with your friends and colleagues. For more insights on web development, technology trends, and digital innovation, stay tuned to this blog.

Next:

Trying Out Lynx.js: A Promising Start, But Not Quite There Yet link