从TypeScript模块访问全局变量

时间:2018-06-22 13:54:10

标签: typescript

编译器编译正常,但在运行时出现以下错误:Uncaught (in promise) ReferenceError: bar is not defined

index.ts

import Foo from "./modules/foo";

const bar: string[] = [];

const foo = new Foo();

foo.ts

declare let bar: string[];

export default class Foo {
    constructor() {
        console.log(bar);
    }
}   

如果要访问foo模块中的bar变量,应该如何进行?

1 个答案:

答案 0 :(得分:0)

所以我现在可以轻松回答我以前的问题:

interfaces.ts

export default interface InterfaceWindow extends Window {
  bar: string[];
}

index.ts

import Foo from "./modules/foo";
import InterfaceWindow from "./interfaces.ts"

declare var window: InterfaceWindow;

window.bar = [];

const foo = new Foo();

foo.ts

import InterfaceWindow from "./interfaces";

declare var window: InterfaceWindow;

export default class Foo {
    constructor() {
        console.log(window.bar); // []
    }
}