You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

NestJS中PrismaService的this.$on报错:类型'string'无法赋值给'never'

解决PrismaService中beforeExit事件的类型错误

方案1:显式指定Prisma事件类型

调用$on时,直接使用Prisma.EventType枚举值代替字符串,让TypeScript正确识别事件类型:

import { INestApplication, Injectable, OnModuleInit} from '@nestjs/common';
import { Prisma, PrismaClient } from '@prisma/client';

@Injectable()
export class PrismaService extends PrismaClient implements OnModuleInit {
    async onModuleInit() {
        await this.$connect();
    }

    async enableShutdownHooks(app: INestApplication) {
        this.$on(Prisma.EventType.beforeExit, async () => {
          await app.close();
        });
    }
} 

方案2:添加类型断言

如果枚举方式不生效,给事件名称添加类型断言,强制TypeScript识别为合法事件类型:

async enableShutdownHooks(app: INestApplication) {
    this.$on('beforeExit' as Prisma.EventType, async () => {
      await app.close();
    });
}

方案3:同步Prisma版本并重新生成Client

确保@prisma/client和prisma CLI版本完全一致,低版本Prisma可能未正确定义beforeExit的类型。执行以下命令更新并重新生成:

npm install prisma@latest @prisma/client@latest
npx prisma generate

方案4:临时调整TypeScript严格配置(不推荐长期使用)

若以上方案均无效,可在tsconfig.json中暂时降低严格模式排查问题:

{
  "compilerOptions": {
    "strict": false,
    "strictNullChecks": false
  }
}

内容的提问来源于stack exchange,提问作者aldoprogrammer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 00:26:02