vardius
vardius

Reputation: 6546

How to instantiate generic object using factory

I am getting method expression is not of function type. With typescript 1.7.5. This is my example:

interface IEntity {
    new(parameters:{id:number}): this;
}

class Repository<T extends IEntity> {​
    constructor(private model:T) {}
​
    create():any {
        return new this.model({id: 1});
    }
}

How can i make it work ?

Should be something like:

class Model implements IEntity {}

let r = new Repository(Model);
let object = r.create();

Upvotes: 0

Views: 701

Answers (2)

Skaza
Skaza

Reputation: 466

This should work.

interface IEntity {
    id:number;
    show(): number;
}

class Repository<T extends IEntity> {​
    ​constructor(private model: {new(id:number): T; }){} //Notice the empty constructor

    create():T {
        return new this.model(2);
    }
}

class Model implements IEntity {
    id:number;

    constructor (id:number){
        this.id = id;
    }
    show():number {
        return this.id;
    }
}

let r = new Repository(Model);
let object = r.create();
console.log(object.show());

It's combination of @DennisJaamann and @John White answers.

Upvotes: 1

Dennis Jaamann
Dennis Jaamann

Reputation: 3565

I believe the syntax should be as follows:

class Repository<T extends IEntity> {​
    ​constructor(){} //Notice the empty constructor

    create():T {
        return new T({id: 1});
    }
}

class Model implements IEntity {}

let r = new Repository<Model>(); //Specify the specific type of IEntity <T>
let object = r.create();

@see http://www.typescriptlang.org/Handbook#generics-generic-classes

Cheers

Upvotes: 0

Related Questions