【发布时间】:2018-09-19 20:08:09
【问题描述】:
我已经创建了一个工厂,它将创建某些类的实例。我想使用泛型来确保返回的所有对象都来自扩展抽象类的子类。
我认为下面显示的createInstance 方法的逻辑可以描述为'createInstance() 将返回一个类型T,该类型被限制为扩展Animal 的类。
如您所见,Lion 扩展了 Animal,但我仍然收到编译器警告 type Lion is not assignable to type T。
abstract class Animal {
abstract makeSound(): void;
}
class Bear extends Animal {
public makeSound() {
console.log('growl');
}
}
class Lion extends Animal {
public makeSound() {
console.log('roar');
}
}
function createInstance<T extends Animal>(type: string): T {
switch(type) {
case 'bear':
return new Bear(); // 'type Bear is not assignable to type T'
case 'lion':
return new Lion(); // 'type Lion is not assignable to type T'
}
}
createInstance().makeSound();
我在TypeScript Generics 文档的末尾读到:
在 TypeScript 中使用泛型创建工厂时,有必要 通过构造函数引用类类型。例如,
function create<T>(c: {new(): T; }): T { return new c(); }
但如果可能的话,我真的不想将类构造函数传递给函数,并且想了解为什么我首先会收到 not assignable to type T 消息。
谢谢
【问题讨论】:
标签: typescript typescript-generics