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

Generics 如何获取对具有指定类型的泛型类的构造函数的引用?,generics,typescript,constructor,Generics,Typescript,Constructor,我有一个这样定义的泛型类 class KeyValuePair<TKey, TValue> { public Key: TKey = null; public Value: TValue = null; } 类KeyValuePair { 公钥:TKey=null; 公共值:TValue=null; } 如何获取创建(例如)KeyValuePair对象的特定构造函数 编辑: 我知道我可以通过调用let x=new KeyValuePair()创建KeyValueP

我有一个这样定义的泛型类

class KeyValuePair<TKey, TValue>
{
    public Key: TKey = null;
    public Value: TValue = null;
}
类KeyValuePair
{
公钥:TKey=null;
公共值:TValue=null;
}
如何获取创建(例如)
KeyValuePair
对象的特定构造函数

编辑:

我知道我可以通过调用
let x=new KeyValuePair()
创建
KeyValuePair
对象,但是,我正在尝试获取构造函数的引用,以便从该函数实例化对象;与此类似,在非工作代码中:

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

让ctorGeneric=KeyValuePair;// 只需使用泛型类型在类中定义构造函数:

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

// b: KeyValuePair<Object, boolean>
let b = new KeyValuePair({}, true)
a.key
// => {}
a.value
// => true
//b:KeyValuePair
设b=newkeyvaluepair({},true)
a、 钥匙
// => {}
a、 价值观
//=>正确
*已更新*

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

这对我来说很好:

let KeyValuePairConstructor = KeyValuePair
// => KeyValuePairConstructor: typeof KeyValuePair
let a = new KeyValuePairConstructor('life', 42)
// => a: KeyValuePair<string, numer>
let b = new KeyValuePairConstructor({}, true)
// => b: KeyValuePair<{}, boolean>
让KeyValuePairConstructor=KeyValuePair
//=>KeyValuePairConstructor:KeyValuePair的类型
设a=新的KeyValuePairConstructor('life',42)
//=>a:KeyValuePair
设b=newkeyvaluepairconstructor({},true)
//=>b:KeyValuePair
这是:

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

let ctor = KeyValuePair;
let pair = new ctor();
将为您提供类型为
KeyValuePairConstructor
ctor2
和类型为
keyvaluepair2


()

Hmm,这不能回答我的问题,因为我想引用KeyVauePair构造函数。把我的问题编辑得更清楚。谢谢。谢谢,你的例子很好用,但我需要一个不需要提供泛型类型的函数,因为我打算用它来反序列化json。请提出这个问题。你需要什么?如果你感兴趣,我接下来的问题是。非常感谢。您需要执行以下操作:{new():KeyValuePair}=KeyValuePair
或类似于我的答案中的类型定义了
KeyValuePair
您完美地回答了我提出的问题!然而,我相信我的问题源于我对TypeScript泛型类的错误理解……如果有人感兴趣,我接下来的问题是。非常感谢。
let KeyValuePairConstructor = KeyValuePair
// => KeyValuePairConstructor: typeof KeyValuePair
let a = new KeyValuePairConstructor('life', 42)
// => a: KeyValuePair<string, numer>
let b = new KeyValuePairConstructor({}, true)
// => b: KeyValuePair<{}, boolean>
class KeyValuePair<TKey, TValue> {
    public Key: TKey = null;
    public Value: TValue = null;
}

let ctor = KeyValuePair;
let pair = new ctor();
type KeyValuePairConstructor<TKey, TValue> = {
    new(): KeyValuePair<TKey, TValue>;
}

let ctor2: KeyValuePairConstructor<string, number> = KeyValuePair;
let pair2 = new ctor2();