我有这个代码:
class BaseModel {
protected getAttribute<T extends BaseModel>(): keyof T | null {
return null;
}
}
class Payment extends BaseModel {}
class Item extends BaseModel {}
class Sale extends BaseModel {
value?: number;
payment?: Payment;
items?: Item[];
protected override getAttribute(): keyof Sale | null {
return 'payment';
}
}
这是真实代码的简化版本.getAttribute
做一些其他的事情,但解决这个简单的实现将解决我的问题.我需要在父类BaseModel
中使用子类自己的实现覆盖函数getAttribute
.该函数只需要返回Sale
(或BaseModel
的任何其他子类)中存在的属性,但我在Sale
中得到了这个错误:
Property 'getAttribute' in type 'Sale' is not assignable to the same property in base type 'BaseModel'.
Type '() => keyof Sale | null' is not assignable to type '<T extends BaseModel>() => keyof T | null'.
Type 'keyof Sale | null' is not assignable to type 'keyof T | null'.
Type 'string' is not assignable to type 'keyof T'.
Type 'string' is not assignable to type 'never'.
我试着把Sale
中的getAttribute
改为:
protected override getAttribute<T extends Sale>(): keyof T | null {
return 'payment';
}
但也没成功Sale
是一个扩展BaseModel
的类,所以Sale
应该等于T
,不是吗?