Mega Man Mega Man - 1 year ago 157
TypeScript Question

TypeScript factory functions that return a generic

(Typescript 2.1.0/VS Code 1.3.0)

I have a

class that looks like

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

return new Promise<T[]>(resolve=>{
request(this.url,function(err,data: T[]){
return new Promise<T>(resolve=>{
request(this.url,function(err,data: T){

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

const enum requestType{
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 Source

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);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download