Generic Type Inference with Class Argument
generics, typescript
Solution
The type information in TypeScript is all erased during compilation, so you can't directly use any of the generic types, for example, at runtime.
So here is what you can do...
You can create classes by name by passing the name as a string. Yes; this involves waving your magic-string-wand. You also need to be aware of anything in your toolchain that may affect the names, for example any minifier that will crush the names (resulting in your magic string being out of sync):
class InstanceLoader<T> {
constructor(private context: Object) {
}
getInstance(name: string, ...args: any[]) : T {
var instance = Object.create(this.context[name].prototype);
instance.constructor.apply(instance, args);
return <T> instance;
}
}
var loader = new InstanceLoader<IActivatable>(window);
var example = loader.getInstance('ClassA');
You can also get type names from instances at runtime, which I have shown in example format below taken from Obtaining TypeScript Class Names at Runtime:
class Describer {
static getName(inputClass) {
var funcNameRegex = /function (.{1,})\(/;
var results = (funcNameRegex).exec((<any> inputClass).constructor.toString());
return (results && results.length > 1) ? results[1] : "";
}
}
class Example {
}
class AnotherClass extends Example {
}
var x = new Example();
var y = new AnotherClass();
alert(Describer.getName(x)); // Example
alert(Describer.getName(y)); // AnotherClass
This would only be relevant if you wanted to generate "another of the same kind" as you could grab the type name and then use the object create stuff to get another.
Problem
I'm having an issue which defining a generic type based on a type I've passed in. I have a piece of code witch “activates” a class, I can’t get the type information from the type parameter so I am passing in class object (not an instance). However this breaks the Type inference. Here is a simplified example of what I'm trying to do: ``` interface IActivatable { id: number; name:string; } class ClassA implements IActivatable { public id: number; public name: string; public address:string; } class ClassB implements IActivatable { public id: number; public name: string; public age: number; } function activator<T extends IActivatable>(type:T): T { // do stuff to return new instance of T. } var classA:ClassA = activator(ClassA); ``` So far the only solution I’ve been able to come up with is to change the type of the `type` argument to `any` and manually set the generic type also (as shown below). However this seems long winded, is there another way to achieve this. ``` function activator<T extends IActivatable>(type:any): T { // do stuff to return new instance of T. } var classA:ClassA = activator<ClassA>(ClassA); ``` Thanks for any help you can give.