4

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?

1
  • The code above works fine, and static myFoo: Foo = new Foo(); is indeed the correct way to initialize it. As explained in the accepted answer, the problem seems to be related to import order when Foo and Bar are in different files. (Just commenting in case anybody else is confused by the question.) Commented Mar 23, 2024 at 16:07

4 Answers 4

9

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.

Sign up to request clarification or add additional context in comments.

1 Comment

indeed, it was because I imported the script files in the wrong order. Thanks!
7

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

class MyClass {
    static initialize() {
        // Initialization
    }
}
MyClass.initialize();

Comments

0

As Jeffery Grajkowski said, your second approach is incorrect. You could just initialize in definition.

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

Comments

-1

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();
      }
   }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.