对模块中全局变量的引用

Reference to global variable from a module

本文关键字:引用 全局变量 模块      更新时间:2023-09-26

我在html标头中声明了一个全局变量,并希望从模块内的类中引用它。如何防止编译器错误:

错误TS2095:找不到符号"selfGlobal"

<html>
    <head>
        <script>
        var selfGlobal = this;
        var globalVariable = 1;
        </script>
    </head>
    <body>   
    <script src="test.js"></script>
    </body>
</html>

测试中.ts

module Test{
    export class TestClass {
        private _privateVariable:any; 
        constructor() {
            this._privateVariable = selfGlobal.globalVariable; // compile error throws here, but the code can run
        }
    }
}

谢谢!Mars

您需要告诉编译器它已经声明:

declare var selfGlobal: any;