【问题标题】:Call a global variable inside module在模块内调用全局变量
【发布时间】:2012-10-26 11:25:55
【问题描述】:

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

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

有可能吗?

【问题讨论】:

标签: typescript


【解决方案1】:

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

declare var bootbox: any;

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

【讨论】:

  • 实际上可以跳过 ': any' 位。
  • 这不是问答格式的好例子,尽管我建议他们添加特定的类型信息,答案显示了他们将如何以及在何处放置它。
  • 对于我们这些打字新手来说,我们应该把declare 声明放在哪里?
  • 这也是全局函数的好解决方案吗?放置类似declare var myFunction: any;?
  • @jonathanrz 是的,如果你想走那么远,它也可以是一个特定的签名,例如declare var myFunction: (input: string) => void;
【解决方案2】:

对于那些还不知道的人,您必须将 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 中,您要定义可能不是源自TypeScript 文件的变量时使用declare 关键字。

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

【讨论】:

    【解决方案3】:

    如果它是您引用但从不变异的东西,请使用const

    declare const bootbox;
    

    【讨论】:

      【解决方案4】:

      Sohnee 解决方案更干净,但你也可以尝试

      window["bootbox"]
      

      【讨论】:

        【解决方案5】:

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

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

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

        const bootbox = BootBox;
        

        这是example

        【讨论】:

          【解决方案6】:
          // 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'
          

          【讨论】:

            【解决方案7】:

            下载bootbox typings

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

            【讨论】:

            猜你喜欢
            • 2016-02-10
            • 2015-03-07
            • 1970-01-01
            • 2013-07-19
            • 1970-01-01
            • 1970-01-01
            • 2016-10-20
            • 2016-09-15
            • 1970-01-01
            相关资源
            最近更新 更多