TypeScript -- 来自全局范围的 new Image()
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25203906/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
TypeScript -- new Image() from global scope
提问by user37057
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
我有一个类 MYMODULE.Image{},但我想实例化一个 HTMLImageElement 类型的对象。当我调用时new Image()
,TypeScript 认为我想实例化 MYMODULE.Image,即使我使用
image: HTMLImageElement = new Image();
Can I somehow explicitly call the global Image class? I tried
我可以以某种方式显式调用全局 Image 类吗?我试过
image: HTMLImageElement = new Window.Image();
but to no avail.
image: HTMLImageElement = new Window.Image();
但无济于事。
A scope resolution operator like C++'s ::Image
would be handy. Perhaps it's there and I just don't see it.
像 C++ 这样的范围解析运算符::Image
会很方便。也许它就在那里,而我只是没有看到它。
Thank you
谢谢
回答by Dick van den Brink
Creating a HTMLImage element can be done like this.
可以像这样创建 HTMLImage 元素。
document.createElement("img");
document.createElement("img");
According to the Mozilla documentation it is the same: https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement.Image
根据 Mozilla 文档,它是相同的: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:
如果您想使用 Image 构造函数,您可能需要创建一个如下所示的新界面:
interface Window {
Image: {
prototype: HTMLImageElement;
new (): HTMLImageElement;
};
}
var a = new window.Image()
回答by basarat
You can do that with a clever use of typeof
:
你可以巧妙地使用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();
}