3

I'm using TypeScript and require.js to resolve dependencies in my files. I'm in a situation where I want to reference a static field of a class in an other class, but in the same internal module (same folder) and I am not able to access it in that specific context. Also, the pre-compiler doesn't show any error in my code, but when accessing the static field at execution, I only get an undefined value.

Here are the relevant files :

Game.ts containing the variable to be accessed

import Scene = require("Scene");
import Stage = require("Stage");

class Game {
    // ...
    static GAME_WIDTH: number = 1920;
    // ...

    public start(): void {
        var currentScene: Scene = new Stage(); // Calls the Stage constructor
    }
}
export = Game;

Launcher.ts entry point of the execution

import Game = require("Game");

console.log(Game.GAME_WIDTH);    // Correctly shows "1920"
var onlyGame: Game = new Game();
onlyGame.start();                

Stage.ts in which I'm trying to refer to Game.GAME_WIDTH

import Game = require("Game");
import Scene = require("Scene");

class Stage implements Scene {
    constructor() {
        console.log(Game.GAME_WIDTH); // Shows "undefined"
    }
}
export = Stage;

Launcher.ts will execute first, creating a Game instance and starting it, which will create a Stage instance that seem to not be able to access Game.GAME_WIDTH anymore. I don't understand why I can access the static variable once but can't do it again later in the execution. And the Visual Studio pre-compiler sees nothing wrong in my code.

Can somebody help me with what's wrong here ?

Thanks !

Kewin Dousse
  • 3,880
  • 2
  • 25
  • 46
  • 1
    **1)** You have the circular dependency problem **2)** module loading order is not defined by the TypeScript language, it is rather left to the module loader and to the script bundler which is unknown in your question **3)** What does the debugger say? – xmojmr Nov 26 '14 at 19:17
  • This comes up reasonably often - there are several ways to avoid the circular dependency: http://stackoverflow.com/questions/26886769/circular-dependency-issue-with-typescript-commonjs-browserify – Fenton Nov 26 '14 at 21:04
  • **1)** `Game` is dependant of `Stage` even if `Game` has finished its `constructor` (which is empty here) method ? **2)** I'm using AMD modules with require.js. I'll edit my question. **3)** The output is too long to be pasted here (and is in french, I'll need to install the English package for convenience when posting them online) – Kewin Dousse Nov 26 '14 at 21:04
  • 1
    @Protectator the short answer is that if they are tightly coupled (i.e. they can't live without each other), put them in the same file / module. – Fenton Nov 26 '14 at 21:06

0 Answers0