Type-Checking JavaScript Files with --checkJs in TypeScript
Up until TypeScript 2.2, type checking and error reporting were only available within .ts
files. Starting with TypeScript 2.3, the compiler can now type-check and report errors for plain .js
files as well:
let foo = 42;
// [js] Property 'toUpperCase' does not exist on type 'number'.
let upperFoo = foo.toUpperCase();
There's a new --checkJs
flag which enables type checking for all .js
files by default. Additionally, three new directives in the form of comments allow for more granular control over which pieces of JavaScript code should be checked:
- Use
// @ts-check
to opt in to type checking for a single file. - Use
// @ts-nocheck
to opt out of type checking for a single file. - Use
// @ts-ignore
to opt out of type checking for a single line.
These options leave you with a blocklist approach and a allowlist approach. Note that either way, the --allowJs
option should be set to true
so that JavaScript files are allowed to be included in the compilation in the first place.
#The Blocklist Approach
The idea behind the blocklist approach is to type-check every JavaScript file by default. This can be achieved by setting the --checkJs
compiler option to true
. You can blocklist specific files by adding the // @ts-nocheck
comment at the top of each of these files.
I would recommend this approach if you have a smallish JavaScript code base that you want to type-check in one go. If an error is reported, you can either fix it right away, ignore the line that caused the error using // @ts-ignore
, or ignore the entire file using // @ts-nocheck
.
#The Allowlist Approach
The idea behind the allowlist approach is to only type-check selected JavaScript files by default. This can be achieved by setting the --checkJs
compiler option to false
and adding the // @ts-check
comment at the top of each of the selected files.
I would recommend this approach if you want to gradually introduce type checking in a large JavaScript code base. This way, you won't be overwhelmed with too many errors all at once. Whenever you're working on a file, consider adding // @ts-check
and fixing potential type errors first, effectively implementing a creeping migration.
#Migrating from JavaScript to TypeScript
Once your entire code base is type-checked, it's a lot easier to migrate from JavaScript (and .js
files) to TypeScript (and .ts
files) entirely. Using either the allowlist or the blocklist approach, you can get quick wins and, at the same time, prepare a migration to a fully statically typed code base, powered by TypeScript.
This article and 44 others are part of the TypeScript Evolution series. Have a look!