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

NestJS项目中BaseEntity类字段无法被子类继承问题咨询

解决方案

问题原因

TypeORM 默认不会将普通类上的列装饰器同步给继承它的实体子类,你需要给公共父类添加 @MappedSuperclass() 装饰器,这个装饰器的作用就是标记该类是所有继承实体的公共映射父类,父类上的所有字段和装饰器都会自动被子类继承。

修正后的代码

第一步:修改 BaseEntity 类

// 先导入所需装饰器
import { MappedSuperclass, PrimaryGeneratedColumn, Column } from 'typeorm';
import { ApiProperty } from '@nestjs/swagger';
// 假设UTC是你自定义的类型,确保已正确导入
import { UTC } from './你的UTC类型路径';

@MappedSuperclass() // 新增这个核心装饰器
export class BaseEntity {
  @ApiProperty({ example: 'c057cc8c-ad1b-4081-ba05-41a648e29f19' })
  @PrimaryGeneratedColumn('uuid')
  id: string;

  @ApiProperty({ example: '2021-07-23T16:23:17+00:00' })
  @Column({ nullable: true })
  archivedAt: UTC;

  @ApiProperty({ example: '2021-07-23T16:23:17+00:00' })
  @Column({ nullable: false })
  createdAt: UTC;

  constructor(partial: Partial<BaseEntity>) {
    Object.assign(this, partial);
  }
}

第二步:优化子类继承代码(可选,减少冗余)

你之前的子类构造函数调用 super() 时没有传参数,还重复写了 Object.assign,可以直接复用父类的构造逻辑:

import { Entity, Column } from 'typeorm';
import { ApiProperty } from '@nestjs/swagger';
import { BaseEntity } from './BaseEntity的路径';

@Entity()
export class Book extends BaseEntity {
  @ApiProperty({ example: 'Harry Potter' })
  @Column({ nullable: false })
  title: string;

  constructor(partial: Partial<Book>) {
    // 直接把partial传给父类构造函数即可,不用再重复写Object.assign
    super(partial);
  }
}

额外注意事项

  • 确保你安装的TypeORM版本和当前NestJS项目依赖的@nestjs/typeorm版本兼容
  • 如果还有字段未被识别的问题,可以检查父类的字段访问修饰符不要设置为private,至少为protected或public

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 04:15:05