Mega Man Mega Man - 4 months ago 32
TypeScript Question

TypeScript factory functions that return a generic

(Typescript 2.1.0/VS Code 1.3.0)

I have a

Request
class that looks like

export default class Request<T>{
static name = "adf";
private url:string;
constructor(url:string){
this.url = url;
}

list(){
return new Promise<T[]>(resolve=>{
request(this.url,function(err,data: T[]){
resolve(data);
})
});
}
get(id:number){
return new Promise<T>(resolve=>{
request(this.url,function(err,data: T){
resolve(data);
});
});
}
}


and I'm trying to create a factory function like so:

const enum requestType{
machine,
part
}
export default function(type: requestType): Request<T>(T.endpoint){
return new Request<Machine>(Machine.endpoint);
}


I get the error
cannot find name T
, and a complaint about using an implicit any. What's the proper way to make a factory function that returns a generic?

Answer

If you want to have a generic function then it needs to have the generic type decelration:
function fn<GenericType>(....

Based on your code, you function should look more like this:

function factory<T>(type: requestType): Request<T> {
    switch(type) {
        case requestType.machine:
            return new Request<T>(Machine.endpoint);

        case requestType.part:
            return new Request<T>(Part.endpoint);
    }

    return null;
}

And then you call it like this:

let request: Request<Machine> = factory(requestType.machine);