Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript saves type as undefined

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?

like image 250
julian Avatar asked Dec 20 '25 11:12

julian


1 Answers

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;
like image 146
Nitzan Tomer Avatar answered Dec 22 '25 23:12

Nitzan Tomer