Home > Back-end >  How to type a variable for a Prisma select property
How to type a variable for a Prisma select property

Time:10-22

I’m looking for a way to define a Prisma select statement and then use it in multiple places. For example:

const userSelect: Prisma.UserSelect = {
    id: true,
    name: true,
}

const user = await prisma.user.findUnique({
    where: { id: 1 },
    select: userSelect
})

const posts = await prisma.post.findMany({
    where: { authorId: 1 },
    select: {
        id: true,
        user: {
            select: userSelect
        }
    }
})

However, this isn’t working properly. When using userSelect in the queries, the queries know userSelect is of the expected type Prisma.UserSelect, but they don’t know which fields have actually been selected. This ends up typing both user and posts.user to be {}.

A different approach would be to instead write userSelect like this:

const userSelect = {
    id: true,
    name: true,
} as const;

That works in the query and correctly types the query result. However, now I lose type safety and autocomplete in the definition of userSelect.

Can someone think of a solution that would work correctly in the query select property, the query result, and that would also allow type safety in the definition of the select object?

CodePudding user response:

In TS 4.9 , you would use satisfies for this:

const userSelect = { ... } satisfies Prisma.UserSelect;

This maintains the type of userSelect while still checking and autocompleting inside the brackets.

The canonical solution to this problem in TS4.8 is to use a generic helper function:

function makeUserSelect<T extends Prisma.UserSelect>(t: T): T { return t; }

const userSelect = makeUserSelect({ ... });
  • Related