TypeScript checking in JavaScript file in Visual Studio 2017: –checkJs, // @ts-check, // @ts-nocheck, // @ts-ignore

Enabling TypeScript checking in JavaScript file in Visual Studio 2017

With TypeScript 2.3 and later, we can enable type-checking and reporting errors directly in JavaScript files.

1. type-checking and reporting errors can be enabled for all JavaScript files using checkJs compiler option

For this add tsconfig.json file in web application root directory with content as shown below. then tsconfig.json file serves as configuration file for the TypeScript compiler (tsc) and used to specify the root files and the compiler options required for compilation.

Here:

In the “Compiler Options“, we have set:

“allowJs”: true – to allow JavaScript files to be compiled.

“checkJs”: true –  to report errors in JavaScript files.

“noEmit”: true – to not emit outputs.

“noUnusedLocals”: true –  to report errors on unused locals.

“noUnusedParameters”: true – to report errors on unused parameters.

“target”: “es5” – ECMAScript target version

Full list of compiler options are available here.

In the above tsconfig.json configuration, we have include all files under “Scripts” folder. Also, we have set "compileOnSave": true  to generate all files for a given tsconfig.json upon saving.

Example:  add sample.js file in “Scripts” folder

and you should be able to see following warnings and errors:

TypeScript Error 4

2. type-checking and reporting errors can be disabled at individual file level using // @ts-nocheck comment

You can selectively disable type-checking and reporting errors on JavaScript files using // @ts-nocheck comment. sample.js file with // @ts-nocheck comment.

3. type-checking and reporting errors can be enabled at individual file level using // @ts-check comment

Remove "checkJs": true from tsconfig.json. Now you can selectively enable type-checking and reporting errors on JavaScript files using // @ts-check comment.

and add a comment // @ts-check to JavaScript file for which you want to enable type-checking and errors reporting as shown below.

The above code will give following warnings after adding // @ts-check :

TypeScript Error

TypeScript Error1

3. type-checking and reporting errors can be ignored on specific lines of JavaScript file using // @ts-ignore comment on the preceding line

With // @ts-ignore comment on the preceding line, the following code will not give “Unused Parameter Error”.

Note: If  TypeScript is not already installed, it can be downloaded from here. Also, TypeScript Definitions (d.ts) for jQuery can be installed using jquery.TypeScript.DefinitelyTyped Nuget Package as shown below:

jquery.TypeScript.DefinitelyTyped Nuget Package

Happy Coding !!!

Kapil Khandelwal

Web Developer, Blogger, Microsoft Certified Professional (MCP), DZone's Most Valuable Blogger (MVB)

Leave a Reply

Your email address will not be published. Required fields are marked *