Search code examples
modulestatictypescriptinternal

Reference a class' static field of the same internal module but in a different file?


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 file, but in the same internal module (same folder) and I am not able to access it, even if the Visual Studio pre-compiler does not show any error in my code. I have the following situation :

Game.ts

class Game {
    // ...
    static width: number = 1920;
    // ...
}
export = Game;

Launcher.ts

/// <reference path='lib/require.d.ts'/>
import Game = require("Game");

var width: number = Game.width;
console.log(width); // Hoping to see "1920"

And the TypeScript compiler is ok with all of this. However, I keep getting "undefined" at execution when running the compiled Launcher.ts. It's the only reference problem I'm having in my project, so I guess the rest is configured correctly.

I hope I provided all necessary information, if you need more, please ask

Any help is appreciated, thanks !


Solution

  • Your code seems sound, so check the following...

    You are referencing require.js in a script tag on your page, pointing at Launcher (assuming Launcher.ts is in the root directory - adjust as needed:

    <script src="Scripts/require.js" data-main="Launcher"></script>
    

    Remove the reference comment from Launcher.ts:

    import Game = require("Game");
    
    var width: number = Game.width;
    console.log(width); // Hoping to see "1920" 
    

    Check that you are compiling using --module amd to ensure it generates the correct module-loading code (your JavaScript output will look like this...)

    define(["require", "exports", "Game"], function (require, exports, Game) {
        var width = Game.width;
        console.log(width); // Hoping to see "1920" 
    });
    

    If you are using Visual Studio, you can set this in Project > Properties > TypeScript Build > Module Kind (AMD)