我有一个typescript文件叫做Projects。我想引用一个在bootstrap插件bootbox.js中声明的全局变量。
我想从TypeScript类中访问一个名为bootbox的变量。
这可能吗?
我有一个typescript文件叫做Projects。我想引用一个在bootstrap插件bootbox.js中声明的全局变量。
我想从TypeScript类中访问一个名为bootbox的变量。
这可能吗?
当前回答
你需要告诉编译器它已经被声明:
declare var bootbox: any;
如果你有更好的类型信息,你也可以添加它,代替任何。
其他回答
// 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'
如果它是你引用但从未改变的东西,那么使用const:
declare const bootbox;
对于那些还不知道的人,你必须把declare语句放在类的外面,就像这样:
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文件的变量。
这就像你告诉编译器,我知道这个变量在运行时有一个值,所以不要抛出编译错误。
我现在要下载驱动程序typings
然后在.ts文件中添加对它的引用。
Sohnee解决方案更清洁,但你也可以尝试
window["bootbox"]