How to extend globalThis/global type?

Viewed 1627

I'm working on a typescript project with Prisma and I saw this code on this guide that is using typescript. However my linter gives me errors for the following 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;

The error message for lines 8,9,11 (for global.prisma) is the following

Element implicitly has an 'any' type because type 'typeof globalThis' has no index signature. ts(7017)

How can I extend the type of globalThis or global with Prismaclient so that it works as intended?

1 Answers

Here is the solution suggested in Best practice for instantiating PrismaClient with Next.js in the Prisma docs.

import { PrismaClient } from '@prisma/client'

declare global {
  var prisma: PrismaClient | undefined
}

export const prisma =
  global.prisma ||
  new PrismaClient()

if (process.env.NODE_ENV !== 'production') global.prisma = prisma

Alternative Solution

You could just explicitly cast global to any. Abusing casts can defeat the value of using typescript, but in this specific context I don't see any harm or risk.


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


Related