
可能题目说得比较抽象,例如我们有个类:
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)应该怎么写才能实现我的需求。
1 gucheen 2018 年 2 月 9 日 createDog(constructor: typeof Dog) createDog(constructr: new(name: string) => Dog) 或者建一个对应 Dog 的 interface |
2 sunjourney 2018 年 2 月 9 日 interface DogCreator { new(name: string): Dog } function createDog(constructor: DogCreator): Dog { return new constructor('Teddy'); } 你的单词写错了,看得我很难受。。。 |
3 sunjourney 2018 年 2 月 9 日 另外,没必要这样写,perfer DI over FactorCreator |
4 sunjourney 2018 年 2 月 9 日 FactoryCreator |
5 VDimos 2018 年 2 月 9 日 via Android typescript 文档里面有提到的,在接口那一章。 interface Test { new constructor():Dog } 这样就行了 |
6 qiuyk OP @sunjourney 哈哈 其实只是举个例子 也没想用工厂 只是这边实现有个形参需要传个构造函数而已 谢谢啦(本来想礼貌性道歉 结果你也拼错了 2333333 ) |