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.
CodePudding user response:
According to the docs you need to declare the variable global
first:
import { PrismaClient } from '@prisma/client'
declare global {
var prisma: PrismaClient | undefined
}
export const prisma =
global.prisma ||
new PrismaClient({
log: ['query'],
});
if (process.env.NODE_ENV !== 'production') global.prisma = prisma;
You can also have a separate file globals.d.ts
with the declaration in it.
CodePudding user response:
I could reproduce the same error with strict mode to true and @types/node
package version 16
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;