Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic Type Inference with Class Argument

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.

like image 529
Antony Jones Avatar asked Jul 10 '14 13:07

Antony Jones


People also ask

What is infer generic type arguments?

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.

Which types can be used as arguments of a generic type?

The actual type arguments of a generic type are. reference types, wildcards, or. parameterized types (i.e. instantiations of other generic types).

What is a generic argument?

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.

How do you declare a generic type in a class?

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.


1 Answers

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);
like image 61
blorkfish Avatar answered Oct 20 '22 02:10

blorkfish