Cannot find name ‘ResizeObserver’ error in TypeScript – Cause and solution

If you are having trouble with the error message: “Cannot find name ‘ResizeObserver'”, this article is for you. This error arises when you use the ‘ResizeObserver’ constructor without installing its types. Install the typings for ‘ResizeObserver’ to resolve this error. Keep reading for detailed information.

Why does this error occur?

The error message: “Cannot find name ‘ResizeObserver'” in TypeScript tells us that the name ‘ResizeObserver’ does not exist. Therefore, TypeScript cannot find it in your project.

This error occurs most likely because you have not installed the typings for ‘ResizeObserver’.

Solved – Cannot find name ‘ResizeObserver’ error in TypeScript

Before starting the installation, you should open the ‘tsconfig.json’ file and ensure the ‘DOM’ string is added to the ‘lib’ array in the ‘compilerOptions’ object. For instance, your ‘tsconfig.json’ should be like this:

{
    "compilerOptions": {
        "lib": [
            "es2019",
            "DOM"
            // ... other settings
        ],
        // ... other settings
    }
}

The ‘DOM’ string allows us to get the browser API’s typings. If the ‘lib’ array does not contain the ‘DOM’ string, you must add it to the ‘lib’.

To install the ResizeObserver’s types in TypeScript, you can open the terminal at the root directory of your project and run this command:

npm i -D @types/resize-observer-browser

After successfully executing the above command, we still have one more step to complete the installation. Open the ‘tsconfig.json’ file and add the types of the ‘ResizeObserver’ in the ‘types’ array as follow:

{
    "compilerOptions": {
        "lib": [
            "es2019",
            "DOM"
            // ... other settings
        ],
        "types": [
            "resize-observer-browser"
        ],
        // ... other settings
    }
}

The error seems to be resolved at this point, and you can already start working with the ‘ResizeObserver’ constructor. For example:

const testResizeObserver = new ResizeObserver((e) => {
    // Do something to each entry
});

In case the error persists, try to remove the ‘node_modules’ folder and the ‘package-lock.json’ file. After that, run the ‘npm install’ command. You can do all these things with the commands below:

rm -rf node_modules
rm -f package-lock.json
npm install

After executing the above commands, we recommend you restart the IDE and development server before continuing with your work to avoid unexpected errors.

Summary

In summary, we have shown you the cause and solution for the “Cannot find name ‘ResizeObserver'” error in TypeScript. We need to install the typings for ‘ResizeObserver’ before we can use it. That’s the end of this article. Hopefully, the information we provide will be helpful to you.

Leave a Reply

Your email address will not be published. Required fields are marked *