by: Helge, published: Oct 8, 2020, in

JavaScript Development with Type Checking in VS Code

This is a collection of things I found helpful for JavaScript development in Visual Studio Code, specifically the easy availability of TypeScript’s advanced type checking and error reporting functionality. Please note that this post is about lightweight JavaScript without any frameworks.

JavaScript Type Checking

Enabling JavaScript Type Checking

tsconfig.json

Create a file called tsconfig.json with the following content in the same directory as your JavaScript files:

{
   "compilerOptions":
   {
      "outDir": "./dist",
      "allowJs": true,
      "checkJs": true,
      "module": "ES2015",
      "target": "ES2015"
   },
   "exclude": ["node_modules", "**/node_modules/*", "dist"]
}

globals.d.ts

Create a file called globals.d.ts with the following content in the same directory as tsconfig.json:

interface Window
{
   chrome: any;
}

declare var browser: any;

Configuring JavaScript Type Checking

The coolest thing about this setup is that you do not have to configure a thing in VS Code. It does this out of the box and just requires a few hints and nudges through configuration files.

tsconfig.json

The tsconfig.json file tells VS Code that this is a TypeScript project that allows JavaScript, too ("allowJs": true). Type checking for JavaScript files is enabled through "checkJs": true.

The ES2015 options specify the minimum version of JavaScript supported in the project. Make sure to check browser compatibility for every language feature you plan to use, e.g. on caniuse, or, in excruciating detail, in kangax’ ECMAScript compatibility table on GitHub. A nice quick JaveScript versions overview has been published by W3Schools.

I had to add the dist directory as an outDir and exclude option to work around the error message cannot write file ‘somesourcefile.js’ because it would overwrite input file.

globals.d.ts

This is where you can add missing type definitions that would otherwise lead to errors. In a Chrome browser extension, we are using window.chrome, for example, or browser.storage and browser.browserAction.

Keyboard Shortcuts for JavaScript Type Checking

Problems (Errors and Warnings)

  • Navigate to the next/previous error or warning: F8/Shift+F8
  • Open/close the errors and warnings panel: Ctrl+Shift+M

IntelliSense

  • Open the suggestions widget: Ctrl+Space
  • Peek at a symbol’s definition: Alt+F12 (close with Esc)
  • Go to definition: F12

References

Previous Article How to Check Which Bluetooth A2DP Audio Codec Is Used on Windows
Next Article VS Code as Markdown Note-Taking App