首页 > 解决方案 > TypeScript - 找不到名称“图像”

问题描述

我正在尝试创建一个图像加载类,但在数组定义中它会抛出一个错误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;
}

标签: typescript

解决方案


不幸的是,我无法发表评论,因为我没有足够的代表,但我只想在 Aleksey L 的解决方案中再添加一件事。

通常,如果您使用 VS-Code 或 Webstorm 或任何具有智能感知功能的编辑器,您可以将鼠标悬停在“ new Image()”上,它会告诉您它的类型。

所以在这种情况下,你会知道 img 实际上是一个 HTMLImageElement:

let img: HTMLImageElement = new Image();

然后您会立即意识到您的数组不正确,因为图像不是type Image类型而是类型HTMLImageElement,您可以立即将数组调整为HTMLImageElement[].

克鲁,乔治

PS:如果您对此表示赞同,我会很高兴,我讨厌写这么长的帖子而不是简短的评论。


推荐阅读