Enabling Type-Checking with checkJs
You'll learn how to configure TypeScript to type-check your JavaScript files using JSDoc annotations, giving you type safety without converting to .ts files.
What checkJs Does
The checkJs compiler option tells TypeScript to apply type-checking rules to .js files in your project, not just .ts files. This is a powerful migration tool: you get compile-time error detection in JavaScript code without renaming anything.
When enabled, TypeScript uses type inference to understand your JavaScript code and validates it using the same rules it applies to TypeScript files. Any JSDoc annotations you've written become enforceable type declarations.
Think of it like turning on spell-check for a document you've already written—the document itself doesn't change format, but you suddenly see where improvements are needed.
Enabling checkJs Globally
In your tsconfig.json:
{
"compilerOptions": {
"allowJs": true,
"checkJs": true,
"noEmit": true
}
}
Now TypeScript will type-check all JavaScript files in your project. The noEmit flag means you're only checking types, not compiling output—perfect for validating existing JavaScript.
How It Works with JSDoc
Without checkJs, JSDoc is just comments. With it enabled, JSDoc becomes type enforcement:
/**
* @param {string} name
* @param {number} age
* @returns {string}
*/
function greet(name, age) {
return `Hello, ${name}. You are ${age} years old.`;
}
// TypeScript now catches this error:
greet(42, "thirty"); // Error: types don't match JSDoc
File-Level Control
You don't have to enable checking everywhere. Use directives for granular control:
// @ts-checkat the top of a file enables checking for that file only// @ts-nocheckdisables checking even whencheckJsis on globally
This lets you migrate file-by-file while keeping the global setting off.
When to Use checkJs
Enable checkJs when you want type safety during migration but aren't ready to convert files to TypeScript yet. It's ideal for catching errors in large JavaScript codebases incrementally, especially when paired with JSDoc annotations you may already have.
Key Takeaway: The checkJs compiler option turns TypeScript's type-checker on for JavaScript files, enforcing JSDoc annotations and inference-based types without requiring conversion to .ts files.