我正在尝试创建一个基类,其属性为同一类中另一个方法的返回类型,这可以在子类中更改它的类型:
abstract class Base {
public get = {
...this.getBase(),
hello() {}
}
protected abstract getBase<T extends object>(): T;
}
class InheritBase extends Base {
// Error: '{ hello2(): number; }' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint 'object'
protected getBase() {
return {
hello2() {return 3},
}
}
}
class InheritBase2 extends Base {
// Error: '{ differentHello(): number; }' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint 'object'
protected getBase() {
return {
differentHello() {return 4},
}
}
}
const c = new InheritBase();
// ok
c.get.hello();
// Error: hello2 doesn't exist on property get
c.get.hello2();
const d = new InheritBase2();
// ok
d.get.hello();
// Error: differentHello doesn't exist on property get
d.get.differentHello();
这个想法是为了避免在每个子类中重新定义属性 get
,同时也在派生类中获取实际类型。
如何实现?