JohnC
JohnC

Reputation: 367

How to get a reference to the constructor of a generic class with types specified?

I have a generic class defined as such.

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

How can I get the specific constructor that creates (as an example) the KeyValuePair<String, Number> object?

Edit:

I know I can create the KeyValuePair<String, Number> object just by calling let x = new KeyValuePair<String, Number>() However, I am trying to get a reference to the constructor function so that I can instantiate the object from that function; like so, in non-working code:

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

Upvotes: 2

Views: 1144

Answers (2)

Manu Artero
Manu Artero

Reputation: 10243

Just define a constructor in your class using generic types:

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

Now, define a new object with your specific type

// 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

Even better, you could omit the type declaration for KeyValuePair:

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

Another example:

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

* UPDATED *

I am trying to get a reference to the constructor function so that I can instantiate the object from that function

This is working fine for me:

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

Upvotes: 1

Nitzan Tomer
Nitzan Tomer

Reputation: 164129

This:

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

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

Will get you a ctor of type KeyValuePair and pair of type KeyValuePair<{}, {}>.

But this:

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

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

Will get you a ctor2 of type KeyValuePairConstructor<string, number> and pair2 of type KeyValuePair<string, number>.

(code in playground)

Upvotes: 1

Related Questions