Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript -- new Image() from global scope

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

like image 865
user37057 Avatar asked Aug 08 '26 13:08

user37057


2 Answers

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()
like image 139
Dick van den Brink Avatar answered Aug 11 '26 04:08

Dick van den Brink


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();
}
like image 35
basarat Avatar answered Aug 11 '26 05:08

basarat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!