如何获取对指定类型的泛型类的构造函数的引用?

时间:2016-07-31 02:37:26

标签: generics typescript constructor

我有一个如此定义的泛型类。

class KeyValuePair<TKey, TValue>
{
    public Key: TKey = null;
    public Value: TValue = null;
}

如何获取创建(作为示例)KeyValuePair<String, Number>对象的特定构造函数?

编辑:

我知道我可以通过调用KeyValuePair<String, Number>创建let x = new KeyValuePair<String, Number>()对象但是,我试图获得对构造函数的引用,以便我可以从该函数实例化该对象;像这样,在非工作代码中:

let ctorPrimitive = String;
console.log(new ctorPrimitive()); // works
let ctorGeneric = KeyValuePair<String, Number>; // <-- error
console.log(new ctorGeneric()); // does not work

2 个答案:

答案 0 :(得分:1)

只需使用泛型类型在类中定义构造函数:

class KeyValuePair<TKey, TValue> {
  public key: TKey = null
  public value: TValue = null
  constructor(aKey: TKey, aValue: TValue) {
    this.key = akey
    this.value = aValue
  }
}

现在,使用您的特定类型

定义一个新对象
// note we are using string and number instead of String and Number
let a = new KeyValuePair<string, number>('life', 42)
a.key
// => 'life'
a.value
// => 42

更好的是,您可以省略KeyValuePair的类型声明:

// typescript knows a is a KeyValuePair<string, number>
let a = new KeyValuePair('life', 42)

另一个例子:

// b: KeyValuePair<Object, boolean>
let b = new KeyValuePair({}, true)
a.key
// => {}
a.value
// => true

*更新*

  

我正在尝试获取对构造函数的引用,以便我可以从该函数实例化该对象

这对我来说很好:

let KeyValuePairConstructor = KeyValuePair
// => KeyValuePairConstructor: typeof KeyValuePair
let a = new KeyValuePairConstructor('life', 42)
// => a: KeyValuePair<string, numer>
let b = new KeyValuePairConstructor({}, true)
// => b: KeyValuePair<{}, boolean>

答案 1 :(得分:1)

此:

class KeyValuePair<TKey, TValue> {
    public Key: TKey = null;
    public Value: TValue = null;
}

let ctor = KeyValuePair;
let pair = new ctor();

会为ctor KeyValuePair类型pairKeyValuePair<{}, {}>类型type KeyValuePairConstructor<TKey, TValue> = { new(): KeyValuePair<TKey, TValue>; } let ctor2: KeyValuePairConstructor<string, number> = KeyValuePair; let pair2 = new ctor2();

但是这个:

ctor2

会为KeyValuePairConstructor<string, number> pair2类型KeyValuePair<string, number>/usr/lib/python3.5类型gimp-image-width

code in playground