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.
Type inference represents the Java compiler's ability to look at a method invocation and its corresponding declaration to check and determine the type argument(s). The inference algorithm checks the types of the arguments and, if available, assigned type is returned.
The actual type arguments of a generic type are. reference types, wildcards, or. parameterized types (i.e. instantiations of other generic types).
Generic arguments, or arguments applied to an entire class or group of opposing arguments, occur frequently in academic debate. Many generic argument positions endure across debate resolutions.
A Generic Version of the Box Class To update the Box class to use generics, you create a generic type declaration by changing the code "public class Box" to "public class Box<T>". This introduces the type variable, T, that can be used anywhere inside the class.
According to the language specification, you need to refer to the class type by it's constructor function. So instead of using type:T
, use type: { new(): T;}
as follows:
function activator<T extends IActivatable>(type: { new(): T ;} ): T {
// do stuff to return new instance of T.
return new type();
}
var classA: ClassA = activator(ClassA);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With