我有一个typescript文件叫做Projects。我想引用一个在bootstrap插件bootbox.js中声明的全局变量。
我想从TypeScript类中访问一个名为bootbox的变量。
这可能吗?
我有一个typescript文件叫做Projects。我想引用一个在bootstrap插件bootbox.js中声明的全局变量。
我想从TypeScript类中访问一个名为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文件的变量。
这就像你告诉编译器,我知道这个变量在运行时有一个值,所以不要抛出编译错误。
其他回答
如果它是你引用但从未改变的东西,那么使用const:
declare const bootbox;
你需要告诉编译器它已经被声明:
declare var bootbox: any;
如果你有更好的类型信息,你也可以添加它,代替任何。
如果你想在整个项目中引用这个变量,在某处创建d.ts文件,例如globals.d.ts。用你的全局变量声明填充它,例如:
declare const BootBox: 'boot' | 'box';
现在你可以在项目的任何地方引用它,就像这样:
const bootbox = 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文件的变量。
这就像你告诉编译器,我知道这个变量在运行时有一个值,所以不要抛出编译错误。
Sohnee解决方案更清洁,但你也可以尝试
window["bootbox"]