简体   繁体   English

TypeScript-找不到名称“ Image”

[英]TypeScript - Name “Image” Not Found

I'm trying to create an image loading class but in the array definition it throws an error saying name "Image" not found , despite creating an image object later in the code. 我正在尝试创建图像加载类,但是在数组定义中,尽管稍后在代码中创建了图像对象,但它抛出一个错误,提示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;
}

I unfortunately can't comment because I don't have enough rep but I just wanted to add one more thing to Aleksey L's solution. 不幸的是,我无法发表评论,因为我没有足够的代表,但我只想在Aleksey L的解决方案中再增加一件事。

Usually if you are using VS-Code or Webstorm or any editor that has intellisense you can hover over the " new Image() " and it will tell you the type of it. 通常,如果您使用的是VS-Code或Webstorm或任何具有智能感知的编辑器,则可以将鼠标悬停在“ new Image() ”上,它将告诉您它的类型。

So in this case you would have known that img is actually a HTMLImageElement: 因此,在这种情况下,您应该知道img实际上是一个HTMLImageElement:

let img: HTMLImageElement = new Image();

Then you would have immediately recognized that your array is incorrect as image is not of type Image but rather of type HTMLImageElement and you could have adjusted your array immediately to HTMLImageElement[] . 然后,您将立即意识到数组不正确,因为image的type Image不是type Image而是HTMLImageElement并且可以立即将数组调整为HTMLImageElement[]

kr, Georg 乔治

PS: I would love if you upvote this I hate to do this long posts instead of short comments. PS:如果您对此表示支持,我很乐意,我不愿发表冗长的文章,而不是简短的评论。

Result of new Image() is HTMLImageElement , so correct typing for the array is new Image()结果是HTMLImageElement ,因此数组的正确键入是
images: Array<HTMLImageElement> or images: 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM