const resources = {
background: '',
player: '',
};
const totalResourceCount = Object.keys(resources).length;
type resourceKey = keyof typeof resources;
export class ResourceLoader {
images: Record<resourceKey, HTMLImageElement>;
loadedCount = 0;
onResourcesLoaded: VoidFunction;
constructor(onLoaded: VoidFunction) {
this.onResourcesLoaded = onLoaded;
const imageMap = {} as Record<resourceKey, HTMLImageElement>;
Object.entries<string>(resources).forEach(([key, source]) => {
const img = new Image();
img.onload = this.onLoad;
img.src = source;
imageMap[key as resourceKey] = img;
});
this.images = imageMap;
}
private onLoad = () => {
this.loadedCount++;
if (this.loadedCount === totalResourceCount) {
this.onResourcesLoaded();
}
};
}
I am looking for a way to define typed resources with keys limited to the ones specified in another object.
Is there an alternative method to write the constructor without using "as"?
Any suggestions on improving the code that maps {key: source}
-> {key: loadedImage}
while tracking the number of items already loaded?