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'会触发类型不匹配的错误。
解决方法
- 从
@prisma/client导入Prisma命名空间 - 将字符串
'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
相关产品推荐
相关产品推荐

