如何在泛型方法

时间:2017-03-16 00:25:11

标签: generics typescript

这段代码不会编译,因为调用CreateItem的第一个参数不是范围内的变量。

  abstract class Catalog<ItemType, IRaw> {
    private CreateItem<ItemType, IRaw>(c: new (raw: IRaw) => ItemType, raw: IRaw): ItemType {
      return new c(raw);
    }
    public ServiceUrl: string;
    public Items: KnockoutObservableArray<ItemType> = ko.observableArray<ItemType>();
    public LoadState: KnockoutObservable<LoadState> = ko.observable<LoadState>(LoadState.NotStarted);
    private loadChunk(): void {
      var that = this;
      if (that.LoadState() === LoadState.NotStarted)
        that.LoadState(LoadState.Loading);
      if (that.LoadState() === LoadState.Loading) {
        $.get(this.ServiceUrl, that.getChunkParameters()).then((result: Array<IRaw>) => {
          if (result.length === 0) {
            that.LoadState(LoadState.Complete)
          } else {
            for (var raw of result){
              let foo = this.CreateItem(ItemType, raw);
              that.Items.push(foo);
            }
          }
        });
      }
    }

如何获取泛型参数ItemType的值的变量引用,以便将其传递给CreateInstance?

1 个答案:

答案 0 :(得分:1)

你做不到。只有类可以用作值。其他类型,特别是泛型参数,不是值,当typescript编译为javascript时不保留它们。该变量必须以某种方式显式提供给loadChunk(),或者作为类似于CreateItem()的值参数,或者作为Catalog类的属性访问,而后者必须以某种方式初始化。

另见Do Typescript generics use type erasure to implement generics?