我得到了method expression is not of function type
。使用typescript 1.7.5
。这是我的例子:
interface IEntity {
new(parameters:{id:number}): this;
}
class Repository<T extends IEntity> {
constructor(private model:T) {}
create():any {
return new this.model({id: 1});
}
}
我怎样才能让它发挥作用?
应该是这样的:
class Model implements IEntity {}
let r = new Repository(Model);
let object = r.create();
答案 0 :(得分:1)
这应该有用。
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());
这是@DennisJaamann和@John White答案的组合。
答案 1 :(得分:0)
我认为语法应该如下:
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
干杯