首页 文章

在Typescript模块中调用全局变量

提问于
浏览
212

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

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

可能吗?

5 回答

  • -4

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

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

  • 12

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

    declare var bootbox: any;
    

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

  • 35

    对于那些不知道的人,您必须将 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 文件的变量的位置 .

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

  • 9

    如果它是你引用但从不变异的东西,那么使用 const

    declare const bootbox;
    
  • 348

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

    window["bootbox"]
    

相关问题