可能题目说得比较抽象,例如我们有个类:
class Dog {
private name: string;
public constructor(name: string) {
this.name = name;
}
public getName(): string {
return this.name;
}
}
然后我有一个函数,接受类作为参数,返回一个对象:
function createDog(constructor: Dog): Dog {
return new construtor('Teddy');
}
const teddy: Dog = createDog(Dog);
但是大家知道这样编译是会报错的,因为createDog接受的是 Dog 实例。我不想用 any,想把我的类限定在 Dog,想问一下createDog(constructor: Dog)应该怎么写才能实现我的需求。