2

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;
}
Bast
  • 72
  • 9

2 Answers2

4

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

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

Burgi0101
  • 66
  • 5
  • 1
    Got upvote, so now you can comment I believe :). Also you can see types in [typescript playground](https://www.typescriptlang.org/play/index.html) – Aleksey L. May 16 '18 at 06:44
  • Yeah, I figured out that I can hover over Image, I just still have C++ in my head so I thought that Image was a sort of wrapper. Thanks for the clarification! – Bast May 16 '18 at 11:08
2

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();
    }

    ...
}
Aleksey L.
  • 35,047
  • 10
  • 74
  • 84