Generics 如何在泛型方法中引用类型参数的值

Generics 如何在泛型方法中引用类型参数的值,generics,typescript,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;

此代码不会编译,因为调用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);
            }
          }
        });
      }
    }
抽象类目录{
私有CreateItem(c:new(raw:IRaw)=>ItemType,raw:IRaw):ItemType{
返回新的c(原始);
}
公共服务URL:字符串;
公共项目:knockoutobservearray=ko.observearray();
public LoadState:KnockoutObservable=ko.observable(LoadState.NotStarted);
私有loadChunk():void{
var=这个;
if(that.LoadState()==LoadState.NotStarted)
LoadState(LoadState.Loading);
if(that.LoadState()==LoadState.Loading){
$.get(this.ServiceUrl,that.getChunkParameters())。然后((结果:数组)=>{
如果(result.length==0){
LoadState(LoadState.Complete)
}否则{
for(结果的原始值){
让foo=this.CreateItem(ItemType,raw);
即.Items.push(foo);
}
}
});
}
}

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

您不能。只能将类用作值。其他类型,尤其是泛型参数,不是值,在将typescript编译为javascript时不会保留它们。必须将该变量显式提供给
loadChunk()
以某种方式,可以作为类似于
CreateItem()
的值参数,也可以作为
目录
类的属性访问,而目录必须以某种方式初始化


另请参见。

我担心情况会是这样。我正在重写以利用继承,但它不像合成那样灵活。哦,好吧,回到绘图板上。