VSCode works but TS compiler throws error: VSCode and TS compiler are not in sync

Viewed 184

I write my project code in VSCode, I have been writing Node.js Express application. I need to access req.user.name from Request object, VSCode complained that name does not exist in user object. So I created global.d.ts file in my project root directory which has the following content:

declare namespace Express {
  interface User {
    userName: string;
    name: string;
    email: string;
  }
}

In my tsconfig.json, I have referenced this file as follows:

{
  "compilerOptions": {
    "typeRoots": ["./node_modules/@types", "./global.d.ts"]
  },
  "include": [/*...*/,"global.d.ts"]
}

After this, VSCode stopped complaining me about the error above, but when I try to compile the project with actual tsc, it throws error. Error from the compiler: error TS2339: Property 'name' does not exist on type 'User'.

For some reason, VSCode and TS compiler are not in sync.

How can I resolve this?

1 Answers

VS Code does not automatically use your project's TS compiler for its TS language services. It comes pre-installed with a version of TSC which it will use unless you tell it otherwise, so can become out of sync.

In order to ensure your IDE is in sync with your project's compiler version, you can tell it where to find your project's TSC binary in the current workspace

If you haven't already, create a .vscode directory at root level of your project, and add a settings.json to it, here you can configure VS Code with project specific settings.

Typically if TSC is installed as a root level node module you would add this to your .vscode/settings.json

{
  "typescript.tsdk": "./node_modules/typescript/lib"
}

There are some GUI based approaches to the above that essentially achieve the same thing, for more info check out these docs...

https://code.visualstudio.com/docs/typescript/typescript-compiling#_compiler-versus-language-service

https://code.visualstudio.com/docs/typescript/typescript-compiling#_using-the-workspace-version-of-typescript

Related