简体   繁体   中英

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.

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.

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.

So in this case you would have known that img is actually a 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[] .

kr, Georg

PS: I would love if you upvote this I hate to do this long posts instead of short comments.

Result of new Image() is HTMLImageElement , so correct typing for the array is
images: Array<HTMLImageElement> or images: HTMLImageElement[] :

class ImageLoader {
    static toLoadCount: number = 0;

    private static images: HTMLImageElement[] = [];

    static onAllLoaded() { };

    static onImageLoad() {
        --ImageLoader.toLoadCount;

        if (ImageLoader.toLoadCount == 0)
            ImageLoader.onAllLoaded();
    }

    ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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