类型Window上不存在XMLHttpRequest

Daw*_*ski 5 typescript

我正在为我的项目开发一个小型异步库.我决定用TypeScript编写它,但我的编译器给我一个错误'XMLHttpRequest' does not exist on type 'Window',正如标题所说.

如果窗口没有XMLHttprequest,我想要实现的是ActiveXObject的创建.

if (window.XMLHttpRequest) {
    xmlhttp = new XMLHttpRequest();
 } else {
    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
Run Code Online (Sandbox Code Playgroud)

我不一定要把它包括在内,但我想知道为什么会这样?


我正在使用的IDE是VS Code(它也向我显示错误)并且我正在编译 gulp-tsify

Tha*_*uni 12

试试这个:

if ((<any>window).XMLHttpRequest) {
    xmlhttp = new XMLHttpRequest();
} else {
    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
Run Code Online (Sandbox Code Playgroud)

事情是,Typescript每个对象都有一个类型,它定义了该类型的属性,有时会从这些定义中删除缺少的属性(或以后动态添加的属性),如果将其强制转换为类型,any则它将处理为匿名类型.