2

I have a class MYMODULE.Image{}, but I want to instantiate an object of type HTMLImageElement. When I call new Image(), TypeScript thinks I want to instantiate MYMODULE.Image, even when I use

image: HTMLImageElement = new Image();

Can I somehow explicitly call the global Image class? I tried

image: HTMLImageElement = new Window.Image(); but to no avail.

A scope resolution operator like C++'s ::Image would be handy. Perhaps it's there and I just don't see it.

Thank you

user37057
  • 49
  • 1
  • 1
  • 5

2 Answers2

7

Creating a HTMLImage element can be done like this.

document.createElement("img");

According to the Mozilla documentation it is the same: https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement.Image

Edit:

If you want to use the Image constructor you might need to create a new interface like below:

interface Window {
    Image: {   
        prototype: HTMLImageElement;
        new (): HTMLImageElement;
    };
}
var a = new window.Image()
Dick van den Brink
  • 13,690
  • 3
  • 32
  • 43
  • 5
    Nope, it looks like TypeScript which compiles to JavaScript ;) – Dick van den Brink Aug 08 '14 at 13:04
  • 1
    I accept document.createElement("img"); as an answer because it is the most hassle free. Thank you for interesting answers! Check out [http://www.sympad.nl/four_in_a_row/][1] for my latest experiment in TypeScript [1]: http://www.sympad.nl/four_in_a_row/ – user37057 Aug 10 '14 at 06:00
1

You can do that with a clever use of typeof :

declare var imageType:typeof Image; // Create a alias so you can refer to the type 
interface Window{
    // Use the `typeof alias` because `Image` would be confused in the context
    Image: typeof imageType; 
}

Complete sample:

declare var imageType:typeof Image;
interface Window{
    Image: typeof imageType;
}

module Foo{
    class Image{}

    var image: HTMLImageElement = new window.Image();
}
basarat
  • 261,912
  • 58
  • 460
  • 511