是否可以从派生类的抽象类方法中声明返回类型。
我计划有一个从许多类派生的抽象类,这个抽象类将包含许多帮助器/实用程序方法,但是它的返回类型会因派生类而异。
下面是一个完全假设的例子来说明我的观点
abstract class List {
public list: any[] = []; // `any` here as it will be different for all derived classes
// again, return `any` here as it will differ for all derived classes
public first(): any {
return this.list[0]
}
}
class Dog extends List {
public list: Puppy[] = [];
}
class Cat extends List {
public list: Kitten[] = [];
}
const dog = new Dog();
dog.first() // should be instance of `Puppy`, but will show as `any`
const cat = new Cat();
cat.first() // should be instance of `Kitten`, but will show as `any`
对于上面的例子,我如何告诉 first()
方法“嘿,你将为 Puppy
类返回 Dog
,为 Kitten
类返回 Cat
}} 类”?
我在这里遗漏了一些简单的东西吗?或者我应该使用组合而不是继承并从类中返回一个辅助函数并删除抽象?