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

NestJS + Prisma 5中PrismaClient.$on报"string不可赋值给never"错误

Prisma 5升级后"string不可赋值给never"编译错误解决

你在将Prisma从4.16版本升级到5.x版本后,原有的NestJS Prisma服务代码出现了"string不可赋值给never"的编译错误,原代码如下:

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

@Injectable()
export class PrismaService extends PrismaClient {
  async enableShutdownHooks(app: INestApplication) {
    this.$on('beforeExit', async () => {
      await app.close();
    });
  }
}

问题原因

Prisma 5重构了客户端的事件系统,$on方法的事件名称参数不再接受原始字符串,而是要求使用官方定义的事件枚举值。类型系统会严格校验传入的事件名称,直接传字符串'beforeExit'会触发类型不匹配的错误。

解决方法

  1. 从@prisma/client导入Prisma命名空间
  2. 将字符串'beforeExit'替换为Prisma.Event.beforeExit枚举值

修改后的代码示例:

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

@Injectable()
export class PrismaService extends PrismaClient {
  async enableShutdownHooks(app: INestApplication) {
    this.$on(Prisma.Event.beforeExit, async () => {
      await app.close();
    });
  }
}

如果需要更明确的类型提示,也可以显式指定事件类型:

this.$on<Prisma.BeforeExitEvent>(Prisma.Event.beforeExit, async () => {
  await app.close();
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 14:47:02