简体   繁体   English

我可以在打字稿中获取通用类型的元数据吗?

[英]Can I get metadata of generic type in typescript?

I have a decorated model class: 我有一个装饰模型班:

@Api('payments/deposit')
export class DepositsModel {
  public id: number;
  public created_at: Date;
  ...

In angular component constructor I'm injecting data service pointing to use my model class: 在角度组件构造函数中,我注入指向使用我的模型类的数据服务:

...
public constructor( 
  private $api: GridApiService<DepositsModel>
...
) {
  this.service = new GridService($api);
  ...
}
...

So, my cool component has a cool service, witch knows the type of data it work with... 因此,我很酷的组件提供了很酷的服务,女巫知道它使用的数据类型...

Should know.. 应该知道..

But how I can to get my model's metadata in my GridApiService? 但是,如何在GridApiService中获取模型的元数据呢? I've tried: 我试过了:

@Injectable()
export class GridApiService<T>{
  constructor(
    $http: HttpClient,
  ) {
    let api = Reflect.getMetadata('Api', T);
  }

And got Error message: 'T' only refers to a type, but is being used as a value here. 并得到错误消息:'T'只引用一个类型,但是在这里被用作一个值。

UPDATE 更新

Can you advice me another way to pass initialization data to my GridApiService, witch should be injected through DI, not created with new keyword? 您能否建议我将初始化数据传递给GridApiService的另一种方法,应该通过DI而不是使用new关键字创建注入?

TypeScript types don't exist at runtime, with the exception of those that can be emitted as metadata via class decorators. TypeScript类型在运行时不存在,但可以通过类装饰器作为元数据发出的类型除外。 Generic types cannot be emitted and don't exist for Angular DI. Angular DI 无法发出泛型类型,并且不存在泛型类型。 GridApiService<DepositsModel> doesn't matter for anything but type checking. GridApiService<DepositsModel>对类型检查无关紧要。

The connection between GridApiService and a DepositsModel should be expressed with class design, for example inheritance: GridApiServiceDepositsModel之间的连接应使用类设计来表示,例如继承:

class DepositsGridApiService extends GridApiService {
  Model = DepositsModel;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM