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?
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.
You can just have the call to initialize immediately follow the class declaration:
class MyClass {
static initialize() {
// Initialization
}
}
MyClass.initialize();
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