How to Get Specific Types from the Prisma Client with Relations

Something I bumped into recently, and one of the standout features of Prisma, is its ability to auto-generate TypeScript types based on your database schema. This means you can enjoy strong type-checking in your codebase, preventing many common mistakes.

When we query with Prisma, we get types out of the box, but what if you want to get just the type of query to reference elsewhere?

Preresequites

I assume before diving in that you already have a project with a schema setup and know how to query with Prisma.

Generating Types

When working with relations in Prisma, predicting the exact shape of the returned data might be challenging, especially when we use include or select. Luckily, Prisma offers ways to get types based on these queries.

Here’s an example of how you would do it.

Suppose you have a User in your schema that you are querying we would do this:

import { PrismaClient, Prisma } from '@prisma/client';

const prisma = new PrismaClient();

// Given this query
async function fetchUserWithCars(id: number): Promise<UserWithCars> {
  return prisma.user.findUnique({
    where: { id },
    include: {
      cars: true,
    },
  });
}

// How we can generate just the types for the above query 
type UserWithCars = Prisma.UserGetPayload<{
  include: {
    cars: true;
  }
}>

By using the Prisma.UserGetPayload we can generate dynamic types based on a query. This helper will be generated for all of the names in your schema. Eg, if you have Car you would update this to Prisma.CarGetPayload.

TypeScriptPrismaTs
Avatar for Niall Maher

Written by Niall Maher

Founder of Codú - The web developer community! I've worked in nearly every corner of technology businesses; Lead Developer, Software Architect, Product Manager, CTO and now happily a Founder.

Loading

Fetching comments

Hey! 👋

Got something to say?

or to leave a comment.