【问题标题】:TypeError while instanciating generic Object实例化通用对象时出现类型错误
【发布时间】: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


【解决方案1】:

我假设entities 包含您要创建的对象的数据。因此它不能用new 调用。你想传入你想要创建的实际类(也许将数据分配给新实例):

class xx {
  factory: Factory = new Factory();
  transform<T>(type: (new () => T), entities: any[]) {
    const tableDtos = new Array<T>();
    for (const entity of entities) {
      const dto: T = this.factory.createEntity(type, entity);
      tableDtos.push(dto);
    }
    return tableDtos;
  }
}

class Factory {
  createEntity<T>(type: (new () => T), data: any): T {
    var r = new type();
    Object.assign(r, data) // guessing a decent implementation here 
    return r;
  }
}

class DataClass { a!: number }

var r = new xx().transform(DataClass, [{ a: 1 }]);
console.log(r);

Play

【讨论】:

  • 谢谢 - 我认为这是解决我的问题的方向。如果我使用此代码,它会给我以下错误:Argument of type "typeof dtoClass" is not assignable to parameter of type 'new () =&gt; dtoClass' 我没有使用 Dto-Class 中的方法 - 我在 Angular-Componente-Class 中使用它来将传入的数据映射到 mor 前端友好的 dto .我将在问题中放入一个实体和 Dto 的示例类。
  • @FlixRo 唯一的问题是EntityTableEntry 有一个带参数的参数,您可以更新构造函数的签名以包含参数:new (p: any) =&gt; T
  • 谢谢 :) 很抱歉这个问题,但参数到底应该放在哪里?如果我将它放入像这样createEntity&lt;T&gt;(type: (new (p: any) =&gt; T), data: any) 的创建中,则会继续显示错误。
  • 没关系 - 我也忘了把它放在transform 中。将 createEntity 减少到 static createEntity&lt;T&gt;(type: (new (p: any) =&gt; T), data: any): T { return new type(data); } 非常感谢您清除此问题! :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-27
  • 1970-01-01
  • 1970-01-01
  • 2011-03-21
  • 2017-08-16
  • 2010-11-05
相关资源
最近更新 更多