如何在泛型方法中引用类型参数的值 [英] How to refer to the value of a type parameter in a generic method

查看:126
本文介绍了如何在泛型方法中引用类型参数的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于调用CreateItem的第一个参数不是作用域中的变量,因此无法编译此代码.

This code won't compile because the first parameter of the call to CreateItem is not a variable in scope.

  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?

How do I get a variable reference to the value of the generic parameter ItemType so I can pass it to CreateInstance?

推荐答案

您不能.只能将类用作值.其他类型(尤其是通用参数)不是值,当将Typescript编译为javascript时不会保留它们.该变量必须以某种方式显式提供给loadChunk(),或者作为类似于CreateItem()的值参数,或者作为Catalog类的属性进行访问,而该类又必须以某种方式进行初始化.

You can't. Only classes can be used as values. Other types, generic parameters in particular, are not values, they are not preserved when typescript is compiled to javascript. That variable must be provided explicitly to loadChunk() somehow, either as value argument similar to CreateItem(), or accessible as a property of Catalog class, which in turn must be initialized somehow.

另请参见> Typescript泛型是否使用类型擦除来实现泛型?.

这篇关于如何在泛型方法中引用类型参数的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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