4

I've got 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 do I specify that I want to instantiate a class which resides in the global module/namespace?

Thank you!

1 Answer 1

2

There are many ways, but i would recommend using document.createElement in whatever way. For example:

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

You could create convenience functions or classes that wrap this for you.

One of the other ways would be for example to create a reference to the original Image class before your class definition:

var ImageElement = Image;

...

export class Image {
    ...
}

var image = new ImageElement()

however it won't be recognized as HTMLImageElement instance, ie no appropriate code completion.

edit: here's my non-working attempt to augment the Window interface as mentioned in the comments:

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

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

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you! While this helps in my particular case, it would be useful if there was an operator to address the global namespace, wouldn't it?
Yes it would. Being able to access window.Image would also do it, however Image is not defined on the Window interface, and i also wasn't able to define it there myself, not sure if that's possible at all.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.