【问题标题】:Typescript: instantiate a generic class with the type parameter value in a variableTypescript:用变量中的类型参数值实例化一个泛型类
【发布时间】:2023-01-22 11:06:55
【问题描述】:

在 TypeScript 中,如何创建泛型类的实例? (1) 当类型参数值在编译时已知,并且 (2) 何时将用作类型参数的类型名称作为字符串值传递?

https://jsfiddle.net/zn71am4v/

interface ITheValue {
  TheValue: string;
}

class Foo implements ITheValue {
  TheValue: string;

  constructor(val: string) {
    this.TheValue = val
  }
}

class Bar implements ITheValue {
  TheValue: string;
  constructor(val: string) {
    this.TheValue = val
  }
}

class Buz<T implements ITheValue> {
  Thing: T
  
  constructor(val: string) {
    this.T = new T(val);
  }
    
  getTheValue(): string {
    return this.Thing.TheValue;
  }
}

function run(whichOne: string, theValue: string): string {
  var f: Foo = new Foo('foo value'); // Well at least this works.
  
  // Can this be made to work? (It can in a proper language like C# :p)
  var buz = new Buz<whichOne>(theValue);

  // Even this doesn't work.
  var buz = new Buz<Foo>(theValue);

  return `The value is: ${buz.getTheValue}.`;
}

document.querySelector("#app").innerHTML = run('Foo', 'the value');

【问题讨论】:

    标签: typescript typescript-generics


    【解决方案1】:

    首先,找一个合适的编辑器,比如https://www.typescriptlang.org/play,然后修复你的 Buz

    class Buz<T extends ITheValue> {
      //        ^ not implements
      Thing: T
      
      constructor(val: string) {
        this.Thing = new T(val);
        //               ^! 'T' only refers to a type, but is being used as a value here.(2693)
      }
        
      getTheValue(): string {
        return this.Thing.TheValue;
      }
    }
    
    
    // This DOES work, you just got a "duplicate buz variable definition" error
    var buz1 = new Buz<Foo>(theValue);
    

    所以,错误是你没有通过T构造函数它不知道该把它带到哪里

    class But<T extends ITheValue> {
      Thing: T
      constructor(TMaker: new (val: string) => T, val: string) {
        this.Thing = new TMaker(val);
      }
    }
    
    new But(Foo, 'test')
    

    会工作正常

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-04
      • 2020-06-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-03
      相关资源
      最近更新 更多