TypeScript: access class in global module / namespace

I have the following situation:

module MyModule { export class Image { ... } var image = Image(); // returns an instance of MyModule.Image } 

However, I want to create an instance of HTMLImageElement, not MyModule.Image. How to indicate that I want to instantiate a class that is in the global module / namespace?

Thanks!

+4
source share
1 answer

There are many ways, but I would recommend using document.createElement any way. For instance:

 var image = <HTMLImageElement>document.createElement('img'); 

You can create convenience functions or classes that port this for you.

One other way, for example, would be to create a link to the source class of the image before defining your class:

 var ImageElement = Image; ... export class Image { ... } var image = new ImageElement() 

however, it will not be recognized as an instance of HTMLImageElement , i.e. there will be no corresponding code completion.

edit : here is my failed attempt to increase the Window interface, as indicated in the comments:

 interface Window { Image: new(width?: number, height?: number) => HTMLImageElement; } 

It compiles correctly (i.e. without errors), but in Visual Studio it is flagged as an error, saying Duplicate Identifier 'Image' , and attempts to create an instance through new window.Image() are marked as new expressions only valid on constructors . Interestingly, it works great on other interfaces, and, as already mentioned, it compiles correctly.

+2
source

Source: https://habr.com/ru/post/1438374/


All Articles