我是 TypeScript 的新手。现在我想为响应数据初始化一个对象,如下所示:
const auth = new ResponseData<Clazz>();
这是我的混音
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 文件中传递泛型类型?
谢谢小伙子!
export class ResponseData<T> extends BaseResponseHelper(T) {}
您读过此页吗? https://www.typescriptlang.org/docs/handbook/mixins.html
您可以通过这种方式对基类和扩展对象使用泛型类型:
export class ResponseData<T> extends BaseResponseHelper<T> {}
但是,您正在使用 mixin 并且 BaseResponseHelper 是一个函数,这意味着在某些时候您应该编写类似的内容
class MyBaseClass
const ResponseData = BaseResponseHelper(MyBaseClass, options)
除非您尝试使用混合类型 https://www.typescriptlang.org/docs/handbook/interfaces.html#hybrid-types
但你可能在这里更明确地表达你的目标