Here is the code snippet I am working with:
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';
}
}
This representation is a simplified version of the actual code. The getAttribute
function performs additional tasks, but cracking this simple implementation will help resolve my issue. My goal is to override the getAttribute
function in the parent class BaseModel
with the child's unique implementation. The function should only return properties existing in Sale
or any other child of BaseModel
. However, when attempting to do so in Sale
, I encountered the following error:
Property 'getAttribute' in type 'Sale' cannot be assigned to the same property in base type 'BaseModel'.
Type '() => keyof Sale | null' is not compatible with type '<T extends BaseModel>() => keyof T | null'.
Type 'keyof Sale | null' is not assignable to type 'keyof T | null'.
Type 'string' cannot be assigned to type 'keyof T'.
Type 'string' cannot be assigned to type 'never'.
I attempted changing the getAttribute
function in Sale
to:
protected override getAttribute<T extends Sale>(): keyof T | null {
return 'payment';
}
However, this alteration also proved unsuccessful. Since Sale
is a class that extends BaseModel
, shouldn't Sale
be equivalent to T
? Any insights on how to correct this issue would be greatly appreciated.