在模块内部调用全局变量


Answers:


404

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

declare var bootbox: any;

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


5
可以略过':any'位。
Oleg Mihailik

37
尽管我建议他们确实添加特定的类型信息,但那并不能成为Q&A格式的一个很好的例子,答案显示了如何放置以及将其放置在何处。
Fenton

14
对于我们打字稿新手来说,该declare声明放在何处?
鲍勃·霍恩

这也是全局函数的好解决方案吗?放置类似的东西declare var myFunction: any;
jonathanrz '18

1
@jonathanrz是的,如果您想走那么远,它也可以是特定的签名,例如declare var myFunction: (input: string) => void;
Fenton

47

对于那些尚不知道的人,您必须像这样将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;
}

TypeScriptclarify关键字中,用于您要定义可能不是源自TypeScript文件的变量的地方。

就像您告诉编译器一样,我知道此变量在运行时将具有一个值,因此不要引发编译错误。




3

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

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

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

const bootbox = BootBox;

这是一个例子


By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.