我可以在打字稿中获得通用类型的元数据吗? [英] Can I get metadata of generic type in typescript?

查看:64
本文介绍了我可以在打字稿中获得通用类型的元数据吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个装饰过的模型课:

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...

应该知道..

但是如何在GridApiService中获取模型的元数据?我尝试过:

But how I can to get my model's metadata in my GridApiService? I've tried:

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

并得到错误消息:'T'仅指一种类型,但在此处被用作值.

更新

您能建议我另一种将初始化数据传递到GridApiService的方法,应该通过DI注入,而不是使用new关键字创建吗?

Can you advice me another way to pass initialization data to my GridApiService, witch should be injected through DI, not created with new keyword?

推荐答案

TypeScript类型在运行时不存在,但可以通过类装饰器作为元数据发出的类型除外.通用类型无法发出,并且对于Angular DI不存在. GridApiService<DepositsModel>除了类型检查外什么都没有.

TypeScript types don't exist at runtime, with the exception of those that can be emitted as metadata via class decorators. Generic types cannot be emitted and don't exist for Angular DI. GridApiService<DepositsModel> doesn't matter for anything but type checking.

GridApiServiceDepositsModel之间的连接应使用类设计来表示,例如继承:

The connection between GridApiService and a DepositsModel should be expressed with class design, for example inheritance:

class DepositsGridApiService extends GridApiService {
  Model = DepositsModel;
}

这篇关于我可以在打字稿中获得通用类型的元数据吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆