node.jstypescriptpostgresqlnext.jsprisma

How to resolve this typescript error on global node.js object


I am following this guide https://vercel.com/guides/nextjs-prisma-postgres to create a full stack app. Typescript is throwing an error in this snippet of code:

import { PrismaClient } from '@prisma/client';
let prisma: PrismaClient;

if (process.env.NODE_ENV === 'production') {
  prisma = new PrismaClient();
} else {
  if (!global.prisma) {
    global.prisma = new PrismaClient();
  }
  prisma = global.prisma;
}

export default prisma;

TypeScript is throwing a ts7017 on the global.prisma:

Element implicitly has an 'any' type because type 'typeof globalThis' has no index signature.

Can someone help me understand this and how to fix? I set 'strict' to false in the tsconfig for the meantime and that supressed the issue for the meantime, though I'm sure having it off defeats the purpose of TS.


Solution

  • I could reproduce the same error with strict mode to true and @types/node package version 16

    Update: see the other answer recommended from the docs here https://stackoverflow.com/a/69851359/1345244

    This should work:

    declare global {
      var prisma: PrismaClient; // This must be a `var` and not a `let / const`
    }
    
    import { PrismaClient } from "@prisma/client";
    let prisma: PrismaClient;
    
    if (process.env.NODE_ENV === "production") {
      prisma = new PrismaClient();
    } else {
      if (!global.prisma) {
        global.prisma = new PrismaClient();
      }
      prisma = global.prisma;
    }
    
    export default prisma;