Reputation: 20665
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?
Upvotes: 4
Views: 21466
Reputation: 896
As Jeffery Grajkowski said, your second approach is incorrect. You could just initialize in definition.
class Bar {
static myFoo: Foo = new Foo();
}
Upvotes: 0
Reputation: 13148
This requires JQuery, but is what I do to have the equivalent of a 'static constructor'.
namespace SomeNamespace {
$(() => SomeClass.StaticConstructor());
export class SomeClass {
public static StaticConstructor() {
}
}
}
This is also useful as the "entry point" of your application, for example.
namespace SomeNamespace {
$(() => SomeClass.Start());
export class SomeClass {
private static sInstance: SomeClass;
public static Start() {
SomeClass.sInstance = new SomeClass();
}
}
}
Upvotes: -1
Reputation: 29739
You can just have the call to initialize immediately follow the class declaration:
class MyClass {
static initialize() {
// Initialization
}
}
MyClass.initialize();
Upvotes: 7
Reputation: 4061
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.
Upvotes: 9