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
相关产品推荐
相关产品推荐

