Error: TypeScript unable to locate file named "Image"

I'm encountering an issue while attempting to construct a class for loading images. The error message states that name "Image" not found within the array definition, even though I create 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;
        }
    

Answer №1

Regrettably, my reputation doesn't allow me to comment, but I wanted to contribute to Aleksey L's solution with an additional point.

If you're using VS-Code or Webstorm, or any editor with intellisense, you can hover over "new Image()" to determine its type.

In this instance, you would have identified img as a HTMLImageElement:

let img: HTMLImageElement = new Image();

This realization would have led you to understand that your array should be of type HTMLImageElement[], not Image.

Sincerely, Georg

P.S.: Your upvote would be greatly appreciated; long posts are not my preference.

Answer №2

When using new Image(), the result is of type HTMLImageElement. Therefore, the correct typing for the array should be either

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

    ...
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The component is expected to return a JSX.Element, however it is failing to return any value

The issue lies with this component: const NavigationItems = (props: {name: string, href: string}[]): JSX.Element => { props.map((item, index) => { return <a href={item.href} key={index}>{item.name}</a> }) }; export default Naviga ...

What is the best way to create a highlighted navigation bar using Angular 2?

Is there a way to keep the navbar active even after refreshing the page in Angular 2? I am currently using CSS to accomplish this, but the active tab is removed upon page refresh. Any suggestions on how to tackle this? HTML:-- <ul class="nav navbar- ...

Transitioning create-react-app from JavaScript to Typescript

A few months ago, I began a React project using create-react-app and now I am interested in transitioning the project from JavaScript to TypeScript. I discovered that there is an option to create a React app with TypeScript by using the flag: --scripts-v ...

Bringing Typescript classes into React-scripts does not act as a constructor

I am currently working on integrating a Typescript file into my existing app using Yarn and React-scripts. Encountered error: Module not found, unable to resolve './DiamondNodeModel' import {DiamondNodeModel} from './DiamondNodeModel&ap ...

Unable to resolve external modules in TypeScript when using node.js

I wanted to integrate moment.js into my node application, so I proceeded by installing it using npm: npm install <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="adc0c2c0c8c3d9ed9f8399839d">[email protected]</a> J ...

Experimenting with a function that initiates the downloading of a file using jest

I'm currently trying to test a function using the JEST library (I also have enzyme in my project), but I've hit a wall. To summarize, this function is used to export data that has been prepared beforehand. I manipulate some data and then pass it ...

Is the array index a string or a number?

Why is it that when looping over the indexes of an array they appear as strings, even though using a string to index an array is not allowed? Isn't this inconsistency puzzling? for (const i in ["a", "b", "c"]) { console.log(typeof i + " " + i + " " ...

Ways to get into the Directive class

@Directive({ selector: '[myHighlight]' }) export class HighlightDirective { static test: number = 5; constructor(private el: ElementRef) { } highlight(color: string) { this.el.nativeElement.style.backgroundColor = color; } } In re ...

What's the best way to utilize the tsconfig.json "types" field within a monorepository setting?

Part 1 - Utilizing the "types" Field When a TypeScript library like library A provides type definitions alongside its normal exports, it looks like this: declare global { function someGlobalFunction(): void; } Library B depends on the type definitions ...

Performing bulk operations on all selected rows in a table using Angular 6

Within my Angular 6 web application, there is a table with checkboxes in each row. My goal is to be able to perform bulk actions on the selected rows, such as deleting them. One approach I considered was adding an isSelected boolean property to the data m ...

Exporting Axios.create in Typescript can be accomplished by following a few simple

My code was initially working fine: export default axios.create({ baseURL: 'sample', headers: { 'Content-Type': 'application/json', }, transformRequest: [ (data) => { return JSON.stringify(data); } ...

Module '. ' or its corresponding type declarations cannot be located

While working on my project with TypeScript and using Cheerio, I encountered an issue when trying to compile it with TSC. The compiler threw the following exception: error TS2307: Cannot find module '.' or its corresponding type declarations. 2 ...

How can I use the target type (and maybe even the property type) as a type parameter within a decorator?

In the process of incorporating a deep-watch property decorator in Angular, the following usage has been implemented: @Component({ /* ... */ }) export class AppComp { @Watch( 'a.b.c', function (last, current, firstChange) { // ca ...

Steps to retrieve the value stored in a variable within an Angular service from a separate component

How can I effectively share question details and an array of options from one component to another using services? What is the recommended method for storing and retrieving these values from the service? In my question-service class: private static ques ...

Managing return types in functions based on conditions

Recently, I developed a function to map links originating from a CMS. However, there are instances where the link in the CMS is optional. In such cases, I need to return null. On the other hand, when the links are mandatory, having null as a return type is ...

The current enablement status does not support the experimental syntax 'flow' (7:8):

Utilizing a Mono repo to share react native components with a react app has presented some challenges. When attempting to use a react native component from react, an error keeps popping up that I can't seem to resolve. I've attempted to follow t ...

Should data objects be loaded from backend API all at once or individually for each object?

Imagine having a form used to modify customer information. This form includes various input fields as well as multiple dropdown lists for fields such as country, category, and status. Each dropdown list requires data from the backend in order to populate i ...

The presence of a setupProxy file in a Create React App (CRA) project causes issues with the starting of react-scripts,

I have implemented the setupProxy file as outlined in the documentation: const proxy = require('http-proxy-middleware'); module.exports = function (app) { app.use( '/address', proxy({ target: 'http ...

NestJS does not recognize TypeORM .env configuration in production build

Currently, I am developing a NestJS application that interacts with a postgres database using TypeORM. During the development phase (npm run start:debug), everything functions perfectly. However, when I proceed to build the application with npm run build a ...

When a React component written in TypeScript attempts to access its state, the object becomes

Throughout my app, I've been consistently using a basic color class: const Color = { [...] cardBackground: '#f8f8f8', sidebarBackground: '#eeeeee', viewportBackground: '#D8D8D8', [...] } export defau ...