我有多个端点返回包含分页详细信息的响应。我想使用一种父类型进行分页,并为 data
参数传入不同的数据类型。
我尝试了以下方法,但这不起作用,因为 @Type
中的语句给出了错误 'T' 仅引用类型,但在此处用作值。
,所以它需要一个值/类而不是类型:
export class PaginatedResponseDto<T> {
@Expose()
@ApiProperty()
skip: number;
@Expose()
@ApiProperty()
take: number;
@Expose()
@ApiProperty()
count: number;
@Expose()
@ApiProperty()
@Type(() => T[]) // <- this is not working, because I cannot use `T` here
data: T[];
constructor(data: any) {
Object.assign(this, data);
}
}
我搜索并 found this ,这基本上是有效的,但不幸的是,它似乎将响应转换了两次,这会导致日期问题。
有没有其他方法可以做到这一点(而不是编写多个 PaginatedResponseDto
类?
最佳答案
你可以沿着这条线做一些事情......
export class PaginatedResponseDto<T> {
@Exclude()
private type: Function;
@Expose()
@ApiProperty()
@Type(opt => (opt.newObject as PaginatedResponseDto<T>).type)
data: T[];
constructor(type: Function) {
this.type = type;
}
}
关于Typescript + NestJs + 类转换器 : How to use generic types in response DTO?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71771803/