部署时报错:Type 'string' is not assignable to type 'never'(Prisma 关联字段问题)


项目在本地开发和测试环境均正常,但在部署时,应用启动失败,日志报错:

bash 复制代码
src/devices/devices.service.ts:14:7 - error TS2322: Type 'string' is not assignable to type 'never'.

报错位置为:

ts 复制代码
// devices.service.ts
return this.prisma.device.create({
   createDeviceDto, // 报错指向这一行
});

经过

检查代码发现,CreateDeviceDto 中定义了 deviceGroupId 字段:

ts 复制代码
// create-device.dto.ts
export class CreateDeviceDto {
  @IsString()
  name: string;

  @IsIP()
  ipAddress: string;

  @IsUUID()
  @IsOptional()
  deviceGroupId?: string; // 类型为 string
}

对应的 Prisma 模型为:

prisma 复制代码
model Device {
  id              String
  name            String
  deviceGroupId   String?
  deviceGroup     DeviceGroup? @relation(fields: [deviceGroupId], references: [id])
}

查看 Prisma 生成的类型定义:

ts 复制代码
// node_modules/.prisma/client/index.d.ts
export type DeviceCreateInput = {
  name: string;
  ipAddress: string;
  deviceGroupId?: never; // 注意:类型是 never
  deviceGroup?: { connect: { id: string } };
};

原因定位

Prisma 在 6.x 版本中,对于通过 @relation(fields: [...]) 定义的外键字段,在创建输入类型中将其标为 never,防止直接赋值。必须通过关系字段 deviceGroup.connect 的方式建立关联。


处理方案

方案一:修改 DTO,使用关系字段(推荐)

ts 复制代码
export class CreateDeviceDto {
  @IsString()
  name: string;

  @IsIP()
  ipAddress: string;

  @ValidateNested()
  @Type(() => DeviceGroupConnectDto)
  @IsOptional()
  deviceGroup?: { connect: { id: string } };
}

class DeviceGroupConnectDto {
  @IsString()
  @IsUUID()
  id: string;
}

前端传参格式:

json 复制代码
{
  "name": "web-server",
  "ipAddress": "192.168.1.10",
  "deviceGroup": {
    "connect": {
      "id": "cmg_abc123"
    }
  }
}

Service 层直接透传:

ts 复制代码
return this.prisma.device.create({
   createDeviceDto,
});

方案二:保持 DTO 不变,在 Service 中转换

ts 复制代码
const { deviceGroupId, ...rest } = createDeviceDto;
return this.prisma.device.create({
   {
    ...rest,
    deviceGroup: deviceGroupId ? { connect: { id: deviceGroupId } } : undefined,
  }
});

最终选择

项目为新系统,MVP 刚完成,前端尚未正式对接,无历史兼容压力

因此,选择方案一:修改 DTO,使用 deviceGroup.connect 模式

选择理由

  • 符合 Prisma 推荐的最佳实践
  • 类型系统完全对齐,避免后续类似问题
  • 为后续支持 createconnectOrCreate 等操作预留扩展性
  • 从一开始就建立统一的关联处理规范,利于团队协作

结果

重新部署后,TypeScript 编译通过,应用正常启动,设备创建功能验证无误。

后续其他模块的关联字段均按此模式统一处理。


#Prisma #NestJS #TypeScript #Deployment #TypeNever #TypeError #数据库关联

相关推荐
死神6544 小时前
Vibe Coding 实战:我用 Nuxt 3+NestJS 做了一个电商运营 SaaS
saas·nestjs·nuxt.js·电商运营·vibe coding
copyer_xyf2 天前
PostgreSQL 做向量检索:一条单库路线
数据库·agent·nestjs
Revolution612 天前
Nest.js 是什么:怎样用它写出第一个后端接口
后端·node.js·nestjs
濮水大叔4 天前
NestJS 与 CabloyJS 的 env/config 架构对比:从环境变量到实例级配置
前端·node.js·nestjs
Allshadow9 天前
Nest.js - 连接数据库
javascript·nestjs
Allshadow12 天前
Nest.js - 目录结构
javascript·nestjs
南一Nanyi13 天前
依赖注入和控制反转
前端·设计模式·nestjs
晓得迷路了14 天前
栗子前端技术周刊第 138 期 - NestJS 12、Astro 7.1、npm 12...
前端·javascript·nestjs
xiaofeichaichai16 天前
NestJS 实战:JWT 登录认证、Token 刷新与安全退出
redis·nestjs·jwt·twitter
无双_Joney18 天前
[四期 - 4] NestJS专栏 - 征召一下大家的意见,非常想知道大家都想看看Nest的哪些方面
前端·后端·nestjs