【发布时间】:2019-12-31 09:16:30
【问题描述】:
我在尝试将 API-Data 转换为 Frontend-Dtos 时收到 TypeError: type is not a constructor。
Transform-Method 看起来像这样:
transform<T>(entities: any[]) {
const tableDtos = new Array<T>();
for (const entity of entities) {
const dto: T = this.factory.createEntity(entity);
tableDtos.push(dto);
}
return tableDtos;
}
我的工厂是这样的:
export class Factory {
create<T>(type: (new () => T)): T {
return new type();
}
}
我从here 那里得到了解决方案。我在这里错过了什么?
DTO
import { Entity} from 'src/models/api/Entity';
export class EntityTableEntry {
id: number;
name: string;
constructor(entity: Entity) {
this.id = entity.ID;
this.name = entity.Name;
}
}
实体
export interface Cost {
ID: number;
Name: string;
Description: string;
Value: number;
}
我想要一个泛型方法的原因是,我需要为每个 API-Call 重新编写转换方法,这完全是一团糟!
【问题讨论】:
-
entities包含什么?你使用它的方式应该包含类(所以你会调用类似(transform([Class1, Class2]))的东西。
标签: typescript generics typeerror instantiation