Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript initialize static variable of a class type

Tags:

typescript

I have two classes Foo and Bar. In class Bar I have a static variable called myFoo and I want it to be automatically initialized:

class Foo {
}

class Bar {
    static myFoo: Foo = new Foo();
}

However, I'm getting this error:

Uncaught ReferenceError: Foo is not defined

If I initialize that static variable in Bar's constructor then it works fine:

class Bar {
    static myFoo: Foo;

    constructor() {
         Bar.myFoo = new Foo();
    }
}

Why is that? What did I do wrong when I tried to initialize the static variable myFoo directly?

like image 224
Chin Avatar asked Jun 20 '14 15:06

Chin


2 Answers

You definitely don't want to do that second thing because that's going to overwrite myFoo every time you construct a new Bar and you certainly don't want that.

What you have here is a run time problem, not a compile time problem. The Foo class has to be loaded before the Bar class is loaded otherwise the static initializer will fail. If both classes are in a single file in the above order it works. If the classes are in separate files and you tell TypeScript to compile to a single file it should figure out the correct order for you (though there are bugs in that area). If you're compiling to separate files you'll need to include the scripts on the page in the correct order to satisfy the dependency.

like image 91
Jeffery Grajkowski Avatar answered Oct 21 '22 05:10

Jeffery Grajkowski


You can just have the call to initialize immediately follow the class declaration:

class MyClass {
    static initialize() {
        // Initialization
    }
}
MyClass.initialize();
like image 37
Oded Breiner Avatar answered Oct 21 '22 06:10

Oded Breiner