class A {
private static readonly letters: { [type: string]: any; } = { 'b' : B }
public static check(): void {
console.log(A.letters)
let letters: { [type: string]: any; } = { 'b' : B }
console.log(letters)
}
}
class B extends A {
}
A.check()
Result:
{ b: undefined }
{ b: { [Function: B] check: [Function], letters: { b: undefined } } }
Why exactly is the first log is undefined?
As @E.Sundin wrote in his comment, class B doesn't exist when class A is evaluated.
You'll need to have a static initializer:
class A {
private static readonly letters: { [type: string]: any; }
public static init() {
(this as any).letters = { 'b' : B }
}
...
}
...
A.init()
A.check()
(code in playground)
Because you wanted A.letter to be readonly there's a cast of this to any otherwise the compiler complains about assignment to a read only property.
Another option is to assign an empty object and later populate it:
class A {
public static readonly letters: { [type: string]: any; } = {};
...
}
class B extends A { }
A.letters["b"] = B;
But then A.letters needs to be public, you can move it outside of A to keep it "hidden":
const letters: { [type: string]: any; } = {};
class A { ... }
A.letters["a"] = A;
class B extends A { }
letters["b"] = B;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With