Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XMLHttpRequest does not exist on type Window

Tags:

typescript

I'm working on a small async library for my projects. I decided to code it in TypeScript, but my compiler is throwing me an error that 'XMLHttpRequest' does not exist on type 'Window', as the title says.

What I wanted to achieve is creation of ActiveXObject if window has no XMLHttprequest.

if (window.XMLHttpRequest) {
    xmlhttp = new XMLHttpRequest();
 } else {
    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}

It's not really necessary for me to include it, but I'm wondering why is that?


IDE I'm using is VS Code (which also shows me the error) and I'm compiling with gulp-tsify

like image 338
Dawid Zbiński Avatar asked Jan 04 '17 22:01

Dawid Zbiński


1 Answers

Try this:

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

The thing is that Typescript has a type for every object where it defines the properties of that type, sometimes there are missing properties (or properties that are added dynamically later) from those definitions, if you cast it to type any then it will deal with it as an anonymous type.

like image 132
Tha'er M. Al-Ajlouni Avatar answered Oct 30 '22 05:10

Tha'er M. Al-Ajlouni