【问题标题】:How to refer to the value of a type parameter in a generic method如何在泛型方法中引用类型参数的值
【发布时间】:2017-03-16 00:25:10
【问题描述】:

此代码无法编译,因为调用 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?

【问题讨论】:

    标签: generics typescript


    【解决方案1】:

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

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

    【讨论】:

    • 我担心可能是这种情况。我正在重写以利用继承,但它不像组合那样灵活。哦,好吧,回到绘图板。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多