There is a blog post discussing the Github issue related to Polymorphic this within static methods. Additionally, there is a question thread on Stack Overflow that addresses this topic here. These resources explore potential solutions and workarounds for handling the issue specifically in static class methods. However, there seems to be a lack of reference on resolving the problem with static class members. We are faced with a scenario where our model class includes several static members containing maps with model fields as keys. In inherited classes, we utilize property decorators to tag these model fields (with the inherited classes solely defining field definitions). The decorator plays a role in adding the fields to the static maps defined in the base class. Refer to the code snippet below or try it out in the playground
function field(): any {
return function (target: Base, propertyKey: ModelFields<Base>, _descriptor: PropertyDescriptor) {
if (!target.constructor.fields) {
target.constructor.fields = {};
}
target.constructor.fields[String(propertyKey)] = String(`s_${propertyKey}`);
};
}
class Base {
['constructor']: typeof Base;
static fields: Record<string, string>;
// The above is intended to be Record<keyof ModelFields<this>, string> but 'this' is not permitted here
}
class A extends Base {
@field()
public propA: string = 'A';
}
class B extends Base {
@field()
public propB: string = 'B';
}
type ModelFields<T extends Base> = Required<Omit<T, keyof Base>>
console.log(B.fields) // Type of B.fields appears to be incorrect at this point
The current definition of static fields
relies on Record<string, string>
, which doesn't specify what keys exist in it, even though we know the valid keys should be keyof ModelFields<this>
. Unfortunately, using this
isn't allowed in this context.
Are there any solutions available to ensure the typing of fields
is accurate?