在Typescript模块中调用全局变量

时间:2012-11-06 13:37:48

标签: typescript

我有一个名为Projects.ts的打字稿文件,我想引用一个名为bootbox.js的bootstrap插件中声明的全局变量。

我想从typescript类中访问一个名为bootbox的变量。

有可能吗?

7 个答案:

答案 0 :(得分:357)

你需要告诉编译器它已被声明:

declare var bootbox: any;

如果您有更好的类型信息,也可以添加,代替any

答案 1 :(得分:39)

对于那些不知道的人,您必须将declare声明放在class之外,就像这样:

declare var Chart: any;

@Component({
  selector: 'my-component',
  templateUrl: './my-component.component.html',
  styleUrls: ['./my-component.component.scss']
})

export class MyComponent {
    //you can use Chart now and compiler wont complain
    private color = Chart.color;
}

TypeScript中,您要使用declare关键字来定义可能不是源自TypeScript文件的变量。

就像你告诉编译器一样,我知道这个变量在运行时会有一个值,所以不要抛出编译错误。

答案 2 :(得分:12)

如果是您引用但从不变异的内容,请使用const

declare const bootbox;

答案 3 :(得分:10)

Sohnee解决方案更清洁,但您也可以尝试

window["bootbox"]

答案 4 :(得分:2)

如果您想在整个项目中都引用此变量,请在某个地方创建d.ts文件,例如globals.d.ts。用您的全局变量声明填充它,例如:

declare const BootBox: 'boot' | 'box';

现在,您可以在项目的任何地方引用它,就像这样:

const bootbox = BootBox;

这里是example

答案 5 :(得分:1)

// global.d.ts
declare global {
  namespace NodeJS {
    interface Global {
      bootbox: string // Specify ur type here,use `string` for brief
    }
  }
}

// somewhere else
const bootbox = global.bootbox
// somewhere else
global.bootbox = 'boom'

答案 6 :(得分:-4)

下载[bootbox typings]( https://www.nuget.org/packages/bootbox.TypeScript.DefinitelyTyped/

然后在.ts文件中添加对它的引用。