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

TypeScript中如何创建继承自Mixin的泛型ResponseData类?

问题描述

我是TypeScript新手,希望初始化如下响应数据对象:

const auth = new ResponseData<Clazz>();

已定义Mixin BaseResponseHelper:

type Constructor<T = object> = new (...args: any[]) => T;

export function BaseResponseHelper<TBase extends Constructor>(Base: TBase, options?: ApiPropertyOptions | undefined) {
  class ResponseDTO {
    @ApiProperty({ description: 'Mã lỗi thực hiện API', example: '0000' })
    @IsString()
    error_code!: string;

    @ApiProperty({
      description: 'Nội dung mã lỗi',
      example: '[XXXX]Thực hiện thành công',
    })
    @IsString()
    error_desc!: string;

    @ApiProperty({
      description: 'Trạng thái thực hiện API',
      example: true,
    })
    @IsBoolean()
    success!: boolean;

    @ApiProperty({
      isArray: true,
      type: () => Base,
      example: () => Base,
      description: 'Cấu trúc data trả về',
      ...options,
    })
    @Type(() => Base)
    @ValidateNested({ each: true })
    data_list!: Array<InstanceType<TBase>>;
  }
  return mixin(ResponseDTO); 
}

尝试编写如下类但无法正常工作:

export class ResponseData<T> extends BaseResponseHelper(T) {}

请问如何在ResponseData.ts文件中正确传递泛型类型参数?


解决方案

核心问题在于**BaseResponseHelper需要接收运行时的类构造函数,而非仅类型层面的泛型参数**。泛型T只是类型标识,无法直接作为构造函数传入Mixin,以下是修正方案:

1. 改为工厂函数实现(推荐)

将ResponseData改成接收类构造函数的工厂函数,直接调用BaseResponseHelper生成目标类:

export function ResponseData<TBase extends Constructor>(Base: TBase, options?: ApiPropertyOptions) {
  return BaseResponseHelper(Base, options);
}

使用方式

初始化时传入Clazz的构造函数:

// 生成对应Clazz的响应类
const AuthResponse = ResponseData(Clazz);
// 实例化响应对象
const auth = new AuthResponse();

2. 保留类形式的替代写法

如果希望贴近原有的类调用形式,可以通过静态方法封装:

export class ResponseData {
  private constructor() {}

  static create<TBase extends Constructor>(Base: TBase, options?: ApiPropertyOptions) {
    return BaseResponseHelper(Base, options);
  }
}

// 使用
const AuthResponse = ResponseData.create(Clazz);
const auth = new AuthResponse();

关键说明

  • TypeScript泛型仅作用于类型检查阶段,而BaseResponseHelper需要的是运行时存在的类构造函数,两者不能直接混用。
  • 原代码中BaseResponseHelper(T)里的T只是类型,没有对应的运行时值,因此会报错,必须传入实际的类(如Clazz)才能让Mixin生成正确类型的响应类。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 02:19:54