rinogo rinogo - 5 months ago 12
AngularJS Question

Inconsistent "Cannot find name 'x'" Typescript errors in VS Code

My app compiles (transpiles) just fine, but Visual Studio Code is still showing a lot of errors:

enter image description here

In some of these cases (e.g.

angular
and
ionic
), the problem is a global variable that is added via our inclusion of Angular/Ionic is not recognized. Most of the errors are of the form "Cannot find name 'angular/ionic/ng" (etc).

To make things even stranger, I've noticed that the file that is initially open when I load VS Code doesn't have any errors at all. The red underlined errors are in the other files in other tabs/editors.

What's going on? How do I get VS Code to consistently acknowledge that these globals/namespaces do, in fact, exist?

Answer

After many sad days of chasing this problem - I finally found a GitHub Issue on the VS Code GitHub that explains what is going on.

tl;dr

My tsconfig.json file was configured incorrectly. To fix it, I removed the files section. You may need to remove it in your project, as well, or perhaps just "fix" it to include all relevant .ts files.

Longer version

Adding a files [section] limits our project to those two files and if you open other files not referenced by those two files then they end up in an isolated virtual project. You either need to leave out the files section (then all .ts files underneath the tsconfig.json file are automatically considered part of the project) or you need to list all files of your project in that section.

My original `tsconfig.json file was:

{
    "compilerOptions": {
        "target": "es5",
        "sourceMap": true,
        "removeComments": true,
        "noImplicitAny": true
    },
    "files": [
        "typings/index.d.ts",
        "src/typings/index.d.ts"
    ]
}

So, VS Code thought that my project only consisted of two files. Other .ts files that I loaded were considered an "isolated virtual project" - not hard to understand why they were generating errors.

I changed my tsconfig.json file to the following:

{
    "compilerOptions": {
        "target": "es5",
        "sourceMap": true,
        "removeComments": true,
        "noImplicitAny": true
    }
}

Problem solved!

Comments