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;
}
2
  • Possible duplicate of JavaScript Preloading Images Commented May 16, 2018 at 2:53
  • 1
    It's not a duplicate. This is about Typescript compilation, not javascript browser loading Commented May 16, 2018 at 3:18

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Got upvote, so now you can comment I believe :). Also you can see types in typescript playground
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!
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();
    }

    ...
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.