Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to type prisma objects in parameters

Tags:

prisma

I have a function that expects a prisma model / instance

How do I actually type this function signature? What I want is the type that is returned from a prisma.SOMETABLE.find like:

const item = await prisma.nftCollection.findFirst()

short code snippet below.


import { Prisma, PrismaClient } from '@prisma/client'
const prisma = new PrismaClient()

export class Buyer {

    async findColl() {
        const item = await prisma.nftCollection.findFirst()
        await this.buyItem(item)
    }

    // this is the param i want to type
    async buyItem(item: SOMETYPE) {
        clog.info('todo - buy', item)
    }
}

more detail here: https://github.com/prisma/prisma/discussions/11737

like image 887
dcsan Avatar asked May 02 '26 04:05

dcsan


1 Answers

In @prisma/client (see node_modules/.prisma/client/index.d.ts) you find the types of your models, which you defined in your Prisma schema. Let's say Item is your model.

Therefore you could do the following:

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

const prisma = new PrismaClient();

export class Buyer {

  async findColl(): Promise<void> {
    const item = await prisma.nftCollection.findFirst();
    await this.buyItem(item);
  }

  async buyItem(item: Item | null): Promise<void> {
    clog.info('todo - buy', item);
  }
}

Item is the accordant type (imported from @prisma/client) and buyItem accepts an argument of Item | null since findFirst returns an Item or null. Of course you could check if item is null before calling buyItem, then it would be just item: Item.

If you add a selection set to findFirst, you might need to use Partial<Item>.

Edit: Just read your Github link. Instead of Item using collection should also be fine. Check node_modules/.prisma/client/index.d.ts if you find the definition of type collection { ... }.

like image 135
pzaenger Avatar answered May 11 '26 11:05

pzaenger



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!