簡體   English   中英

TypeScript-找不到名稱“ Image”

[英]TypeScript - Name “Image” Not Found

我正在嘗試創建圖像加載類,但是在數組定義中,盡管稍后在代碼中創建了圖像對象,但它拋出一個錯誤,提示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;
}

不幸的是,我無法發表評論,因為我沒有足夠的代表,但我只想在Aleksey L的解決方案中再增加一件事。

通常,如果您使用的是VS-Code或Webstorm或任何具有智能感知的編輯器,則可以將鼠標懸停在“ new Image() ”上,它將告訴您它的類型。

因此,在這種情況下,您應該知道img實際上是一個HTMLImageElement:

let img: HTMLImageElement = new Image();

然后,您將立即意識到數組不正確,因為image的type Image不是type Image而是HTMLImageElement並且可以立即將數組調整為HTMLImageElement[]

喬治

PS:如果您對此表示支持,我很樂意,我不願發表冗長的文章,而不是簡短的評論。

new Image()結果是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