DEV Community

Cover image for VS Code - Get type checking in JavaScript easily
Rob OLeary
Rob OLeary

Posted on • Originally published at roboleary.net

VS Code - Get type checking in JavaScript easily

Did you know you can type check JavaScript code in VS Code?

VS Code allows you to leverage some of TypeScript's advanced type checking and error reporting functionality in plain old JavaScript files. And you can even do some quick fixes! This can be done alongside ESLint without any issues.

The type checking is opt-in. You can apply it to an individual file, per project, or everywhere.

Enable checking in individual files

If you want to try it out for a file, just add the comment // @ts-check to the top of a file. For example, the code below tries to multiply a number with a string.

// @ts-check

let x = "blah";
let y = x * 2;
Enter fullscreen mode Exit fullscreen mode

You will see red underlining under the offense to point out the error, and you will see the error in the problems tab.

builtin extension list

Enable checking in your workspace or everywhere

You can enable type checking for all JavaScript files with the JS/TS › Implicit Project Config: Check JS setting.

Alternatively, you can place a jsconfig.json in your root folder, and specify your JavaScript project options. You can add type checking as a compiler option as below:

{
  "compilerOptions": {
    "checkJs": true
  },
  "exclude": ["node_modules", "**/node_modules/*"]
}
Enter fullscreen mode Exit fullscreen mode

The advantage of using jsconfig.json is that you can target the files you want checked through include and exclude.

You can use // @ts-nocheck to disable type checking inside a file if you want to make an exception also.

Add extra type checking with JSDoc comments

JSDoc annotations are used to describe your code and generate documentation. Part of that specification is to add types to variables, through this we get can extra type checking in VS Code.

JSDoc annotations come before a declaration in a comment block. In the example below, I specify a type for the parameter and the return value.

builtin extension list

You can see it catches a mistake when I provide a number as argument for the function call isHoriztonalRule(1).

You can find the full list of supported JSDoc patterns in: TypeScript Reference - JSDoc Supported Types.

Conclusion

Getting type checking in JavaScript is pretty sweet. It is simple and flexible to use. It provides some of the benefits of TypeScript without needing to convert a codebase to TypeScript.

Happy hacking!

Top comments (1)

Collapse
 
robole profile image
Rob OLeary • Edited

miyagi approves