Currently, the structure of your code is not functioning properly due to a static property that can change each time the constructor is called. This type of property cannot be marked as readonly
since its value may change after initialization.
Based on the comments, it appears that this approach does not accurately reflect what you intend to achieve. You actually want the property to have different values for each subclass, rather than for each instance.
To solve this issue, consider making the property an instance property and assigning the appropriate value based on the subclass. You can pass this value from the subclass's constructor:
class Base {
// instance field
readonly key: string;
constructor(_key: string) {
this.key = _key;
}
}
class Foo extends Base {
constructor() {
super('Foo');
}
}
class Bar extends Base {
constructor() {
super('Bar');
}
}
Playground Link
If you are concerned about exposing this property when serializing the object, you could make it a "virtual" property using get
:
abstract class Base {
abstract readonly key: string;
}
class Foo extends Base {
get key() {
return 'Foo';
}
}
class Bar extends Base {
get key() {
return 'Bar';
}
}
Playground Link
By declaring the getter per subclass, the value remains specific to each subclass instead of each instance.
In general, having a "static per subclass" concept is not very practical because static properties are not typically accessed polymorphically. This approach would only be viable if the classes themselves were treated as values, such as:
interface KeyedClass {
readonly key: string;
}
class Foo {
static readonly key = 'Foo';
}
class Bar {
static readonly key = 'Bar';
}
function logKey(cls: KeyedClass) {
console.log(cls.key);
}
logKey(Foo);
logKey(Bar);
Playground Link
Unless you specifically require this functionality, there is no benefit in establishing something as "static per class" since it cannot be accessed polymorphically from an instance context. Using this.key
or Base.key
in this scenario wouldn't provide the desired outcome; you would simply retrieve the base class's static property without adapting to the subclass context where this
belongs to.