2017-03-16 48 views
0

此代碼不會編譯因爲調用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?

回答

0

你不能。只有類可以用作值。其他類型,特別是泛型參數不是值,當typescript被編譯爲javascript時,它們不會被保留。該變量必須明確地提供給loadChunk()某種方式,無論是作爲類似於CreateItem(),或可訪問作爲Catalog類的屬性,這又必須以某種方式初始化值參數。

Do Typescript generics use type erasure to implement generics?見。

+0

我擔心這可能是這種情況。我正在重寫利用繼承,但它不像構圖那樣靈活。哦,回到畫板上。 –

相關問題