Reputation: 18542
I'm trying to instantiate a generic class in TypeScript.
In C# I would have done it like this
class MyPacket<T> {...}
var t = typeof(...);
var genericContainer = typeof(MyPacket<>).MakeGenericType(new[]{ t });
var instance = Activator.CreateInstance(genericContainer);
My use case is that I'm receiving messages from a network. I also have a EventEmitter that expects to be called with the correct type.
(msg: Message): void => {
t: ??? = messageNameToType[msg.name];
const m: RPCConsumerMessage<T> = ???;
emitter.emit(msg.name, m);
}
And the emitter gets used like this:
emitter.on('exampleMessageId', (msg: RPCConsumerMessage<ExampleMessage>) => {
// can now easily use the message in a typesafe way: msg.data.exampleText
});
My question:
What is the equivalent in TypeScript or is the whole approach of instancing a generic type flawed? Is there another pattern that is commonly used for those types of problems in TypeScript?
Upvotes: 1
Views: 1025
Reputation: 250366
Unlike C# where generic class instantiations are actually different classes at runtime, in Typescript generic types arguments are erased at compile time, so different generic classes are actually the same class at runtime.
(msg: Message): void => {
const t: any= messageNameToType[msg.name]; // does not really matter.
const m: RPCConsumerMessage<any> = new RPCConsumerMessage<any>();
emitter.emit(msg.name, m);
}
Upvotes: 1