![](/img/trans.png)
[英]Object name not found in Typescript but is in Javascript
[英]TypeScript - Name “Image” Not Found
我正在尝试创建图像加载类,但是在数组定义中,尽管稍后在代码中创建了图像对象,但它抛出一个错误,提示name "Image" not found
。
class ImageLoader {
static toLoadCount:number = 0;
private static images = Array<Image>();
static onAllLoaded() {};
static onImageLoad() {
--Images.toLoadCount;
if(Images.toLoadCount == 0)
Images.onAllLoaded();
}
static load(path: string) {
++Images.toLoadCount;
let img = new Image();
img.src = "Images/" + path;
img.onload = Images.onImageLoad;
Images.images[path.substring(0, path.length - 4)] = img;
return img;
}
static allImagesLoaded() {
return (Images.toLoadCount == 0);
}
[key: string]: any;
}
不幸的是,我无法发表评论,因为我没有足够的代表,但我只想在Aleksey L的解决方案中再增加一件事。
通常,如果您使用的是VS-Code或Webstorm或任何具有智能感知的编辑器,则可以将鼠标悬停在“ new Image()
”上,它将告诉您它的类型。
因此,在这种情况下,您应该知道img实际上是一个HTMLImageElement:
let img: HTMLImageElement = new Image();
然后,您将立即意识到数组不正确,因为image的type Image
不是type Image
而是HTMLImageElement
并且可以立即将数组调整为HTMLImageElement[]
。
乔治
PS:如果您对此表示支持,我很乐意,我不愿发表冗长的文章,而不是简短的评论。
new Image()
结果是HTMLImageElement
,因此数组的正确键入是
images: Array<HTMLImageElement>
或images: HTMLImageElement[]
:
class ImageLoader {
static toLoadCount: number = 0;
private static images: HTMLImageElement[] = [];
static onAllLoaded() { };
static onImageLoad() {
--ImageLoader.toLoadCount;
if (ImageLoader.toLoadCount == 0)
ImageLoader.onAllLoaded();
}
...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.