Issue #44 (Type-checking in JavaScript)02/22/23
Get Smarter Every Day
Every day Refind picks 5 links from around the web that make you smarter, tailored to your interests. Refind is a must-read newsletter loved by 100,000+ curious minds.
|
|
|
If you're not yet a TypeScript user, or if you use TypeScript but also work with some simpler JavaScript projects without TypeScript, there are a few features in VS Code you can take advantage of. These may improve your code and will help you catch mistakes and bad practices.
First, you can enable basic type checking for any JavaScript file by simply adding the line "
// @ts-check" (without the quotes) to the top of any JavaScript file.
As shown in the screenshot above, when you enable type checking on a single file with the
@ts-check directive, you'll get a red 'problem' warning in the file's tab, as well as the red underline on the problematic line. These aren't JavaScript errors, but they're treated like errors due to the type checking. In this instance the problem is trying to re-declare a variable as a number after it's already been initialized as a string. The message shown in the image is the warning that appears when you hover over the problem spot.
If you like this feature for all your native JavaScript files (i.e. .js files), you can enable it in your settings. Search for "tscheck" in your settings, then enable the option "JS/TS › Implicit Project Config: Check JS", which will appear as
"js/ts.implicitProjectConfig.checkJs": true in your settings.json file.
But again, you may not want the global setting. Using
@ts-check, you can enable it just for one or two files, to see if it's something you want to use more extensively.
Similarly, you may have the global setting enabled to type check all .js files, but maybe you want to disable it for a few files. To disable type checking, add the line "
// @ts-nocheck" to the top of any file.
With this comment in place, now the file doesn't display any of the warnings it did before — even though type checking is enabled globally.
In some cases, there may be a particular JavaScript pattern that you're using that goes against the general type checking guidelines, but you still want to enable type checking for everything else. You can tell VS Code to ignore a specific warning by placing "
// @ts-ignore" on the line above the error.
So once again, although type checking is enabled globally, this particular error is ignored because of the
@ts-ignore directive.
Type checking has become pretty commonplace nowadays, so using the above features may help you write better and more maintainable JavaScript, even if you're not yet a TypeScript user.