3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Prisma Typescriptを利用しているときに、global.prismaがanyになるのをさける

Posted at

Prisma Typescript globa.prisma is not definedを避ける

Ref

TL;DR

index.ts
declare global {
    var prisma: PrismaClient;
}

を追加する。

Description

Prismaを利用し始めた時に、globalThis primsa is not declaredとなっているためその回避方法。

Package

- @prisma/client@2.30.0
- typescript@4.4.2

以下のファイルを想定

lib/prisma.ts
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;

以下のErrorを想定。

型 'typeof globalThis' にはインデックス シグネチャがないため、要素は暗黙的に 'any' 型になります。ts(7017)

解決方法

1. d.tsファイルを作成

types.d.ts
declare global {
  namespace NodeJS {
    interface Global {
      prisma: any;
    }
  }
}

2. next-env.d.tsに追記

nextを利用している際は、1の対応ができないためnex-env.d.tsに追記します

next-env.d.ts
/// <reference types="next" />
/// <reference types="next/types/global" />


declare global {
    namespace NodeJS {
        interface Global {
            prisma: any;
        }
    }
}

3. Errorの箇所ににdeclareをそのまま指定する

lib/prisma.ts
import { PrismaClient } from '@prisma/client';

declare global {
    var prisma: PrismaClient;
}

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;
3
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?