Introduction to checkJs
JavaScript is flexible, but that flexibility can make certain errors difficult to identify before an application runs. A function may receive an unexpected value, a property may be missing from an object, or a variable may be used in a way that does not match its intended purpose.
TypeScript provides the checkJs compiler option to report many type-related problems in JavaScript files. Instead of requiring developers to convert every .js file into a .ts file, this option allows TypeScript to analyze existing JavaScript using the type information it can infer from the code and any available JSDoc annotations.
The checkJs option is particularly useful when maintaining large JavaScript applications, gradually adopting TypeScript, improving editor diagnostics, or adding stronger checks to legacy code. It helps developers identify problems while preserving their existing JavaScript implementation.
1. What Does checkJs Do?
The checkJs option tells TypeScript to report errors in JavaScript files included in the project. It enables JavaScript type checking using information inferred from the implementation, JSDoc annotations, and other types available to the compiler.
Consider the following JavaScript function:
// calculate.js
function add(first, second) {
return first + second;
}
const result = add(10, 20);
console.log(result);
TypeScript can often infer that first and second are numbers from their usage and the available information. However, JavaScript permits many operations that depend on runtime values, so not every unexpected input will automatically produce a diagnostic.
When checking is enabled, you can introduce JSDoc annotations to make the intended contract more explicit. TypeScript can then use that information to identify incompatible calls and other problems.
// calculate.js
/**
* Adds two numeric values.
* @param {number} first
* @param {number} second
* @returns {number}
*/
function add(first, second) {
return first + second;
}
add(10, 20);
// Reported type error when checked:
// add("10", 20);
The annotations help TypeScript understand the intended parameter and return types. When JavaScript checking is enabled, the incompatible string argument can be reported before execution.
Importantly, checkJs does not transform JavaScript into TypeScript, and it does not automatically insert runtime checks. It provides static analysis while the source file remains JavaScript.
2. Enabling checkJs in tsconfig.json
The recommended way to configure checkJs for a project is through tsconfig.json. This file defines how TypeScript should analyze the source files in the project.
{
"compilerOptions": {
"allowJs": true,
"checkJs": true,
"noEmit": true
},
"include": [
"src/**/*"
]
}
Each option serves a different purpose.
allowJs
Allows JavaScript files to participate in the TypeScript project. This is important for projects containing both JavaScript and TypeScript files.
checkJs
Enables reporting of type errors in included JavaScript files. It uses inferred types, JSDoc annotations, and other available type information.
noEmit
Prevents the TypeScript compiler from generating output files. This is appropriate when another tool, such as a bundler, handles the build. Remove or adjust it if your build process relies on tsc to emit JavaScript.
The include pattern tells TypeScript which files and directories to include in the project. Adjust it to match your actual application structure, and make sure the JavaScript files you want to check are not excluded or outside the configured project.
If a project already contains a tsconfig.json file, update its existing compiler options instead of creating conflicting configurations. The appropriate settings depend on the application's build process and current TypeScript setup.
3. Understanding allowJs and checkJs
The allowJs and checkJs options are closely related, but they are not interchangeable. Understanding their individual responsibilities helps you configure mixed JavaScript and TypeScript projects correctly.
| Configuration | Purpose |
|---|---|
| allowJs: false | JavaScript files are not included as project source files through allowJs. |
| allowJs: true | JavaScript files can participate in the project. |
| allowJs: true, checkJs: false | JavaScript files can participate without enabling project-wide checkJs diagnostics. |
| allowJs: true, checkJs: true | Included JavaScript files receive type checking and diagnostics. |
A mixed project can use JavaScript modules alongside TypeScript modules. For example, a TypeScript service may import a JavaScript utility, while other parts of the application remain unchanged. The compiler uses the configuration and available type information to determine what it can check.
Enabling checkJs is not the same as converting a JavaScript file to TypeScript. You can continue writing valid JavaScript syntax, including using JSDoc comments to communicate intended types.
4. Detecting Type Errors in JavaScript
One of the main benefits of checkJs is that it can identify incompatible values before a function executes. The quality of the diagnostics depends on what TypeScript can infer and what information the code provides.
// user.js
/**
* Creates a user display name.
* @param {string} firstName
* @param {string} lastName
* @returns {string}
*/
function createDisplayName(firstName, lastName) {
return firstName + " " + lastName;
}
const displayName = createDisplayName("Asha", "Rao");
// Type error when checked:
// const invalidName = createDisplayName(101, "Rao");
console.log(displayName);
The JSDoc annotations describe a function that expects two strings. TypeScript can report that a numeric first argument does not match the intended parameter type.
Diagnostics are particularly useful when a function is reused across many files. Rather than discovering an incompatible argument only after a particular code path executes, developers can identify the mismatch during development or in a type-checking step.
The compiler cannot catch every possible JavaScript problem. If code uses dynamic property access, untyped external data, or values whose types cannot be inferred precisely, some issues may remain undetected.
5. Using JSDoc to Improve JavaScript Checking
JSDoc is especially valuable when using checkJs because it allows you to document types without introducing TypeScript-specific syntax into JavaScript files. Parameter annotations, return types, named object types, and generic declarations can all provide more accurate information to the checker.
// course.js
/**
* @typedef {Object} Course
* @property {number} id
* @property {string} title
* @property {boolean} published
*/
/**
* Returns the title of a course.
* @param {Course} course
* @returns {string}
*/
export function getCourseTitle(course) {
return course.title;
}
const course = {
id: 101,
title: "TypeScript Fundamentals",
published: true
};
console.log(getCourseTitle(course));
The typedef describes the expected structure of a course. The function references this named type instead of repeating its properties in every comment.
If the function receives an object that does not match the declared structure, TypeScript can report relevant type errors when checking the file.
JSDoc also documents the expected public API for developers using the module. Keep the definitions synchronized with the real implementation, since comments alone do not verify that a runtime object actually has the documented structure.
6. Checking JavaScript Object Properties
JavaScript often uses object literals to represent users, products, application settings, and API data. TypeScript can infer object properties from their initial values and use those inferred types to detect certain invalid operations.
// settings.js
const settings = {
theme: "dark",
notificationsEnabled: true
};
settings.theme = "light";
settings.notificationsEnabled = false;
// Reported as an invalid property access:
// settings.language = "English";
console.log(settings);
TypeScript can infer that settings contains a theme property and a notificationsEnabled property. It can also infer their initial value types and report certain incompatible assignments or unknown property accesses.
The exact diagnostic depends on the inferred type, the context in which the object is used, and the compiler configuration. JavaScript permits dynamic operations, so inferred checking is not equivalent to declaring every object shape explicitly in TypeScript.
If an object's intended shape is important and must be shared across many functions, document it with JSDoc or consider defining a TypeScript interface when the application is ready for that change.
7. Using strict with checkJs
TypeScript offers the strict compiler option, which enables a group of stricter type-checking settings. In JavaScript projects, these settings can help uncover additional problems when combined with checkJs and suitable type information.
{
"compilerOptions": {
"allowJs": true,
"checkJs": true,
"strict": true,
"noEmit": true
},
"include": ["src/**/*"]
}
Strict checking is valuable, but it can reveal many existing issues in a mature JavaScript application. The number and type of diagnostics depend on the existing code, inferred types, available JSDoc annotations, and other compiler settings.
In a project with extensive legacy code, enabling strict checking all at once may create a large list of problems to resolve. Teams can begin with a manageable set of files, add explicit type documentation, and expand the checked surface area as the code improves.
Do not disable strictness indiscriminately just because new diagnostics appear. Review each diagnostic and determine whether the code needs a correction, more accurate annotations, or a deliberate adjustment to the configuration.
8. Running JavaScript Checks from the Command Line
TypeScript checking should be part of a repeatable development workflow. After configuring the project, you can run the TypeScript compiler to analyze the files included by tsconfig.json.
npx tsc --noEmit
The compiler reads the project's configuration, analyzes the included files, and reports diagnostics without emitting output files. This command works well when the project uses another tool for its application build.
For example, you could add a script to package.json:
{
"scripts": {
"typecheck": "tsc --noEmit",
"build": "vite build"
}
}
Running npm run typecheck gives the team a separate command for checking JavaScript and TypeScript files. The build command remains responsible for producing the application output through the chosen build tool.
Make sure the type-checking script runs against the intended tsconfig.json. In repositories with multiple applications or configuration files, you may need to specify the correct project configuration explicitly.
9. Gradually Migrating JavaScript to TypeScript
One of the strongest reasons to adopt checkJs is that it supports a gradual path toward TypeScript. Instead of renaming every JavaScript file and fixing every error in a single migration, you can improve the existing code incrementally.
A practical migration strategy can begin with utility modules, shared data structures, and service functions that many other files depend on. These areas often benefit from clearer function contracts and more reliable type information.
Step 1: Include JavaScript files
Configure allowJs and make sure the existing JavaScript source files are included in the TypeScript project.
Step 2: Enable checking
Turn on checkJs and run the compiler to identify errors and areas where the current type information is insufficient.
Step 3: Add useful JSDoc
Document important parameters, return values, shared object structures, and reusable callback signatures.
Step 4: Fix diagnostics
Correct incompatible operations, improve type descriptions, and add tests where a change may affect runtime behavior.
Step 5: Convert selected files
When useful, convert suitable JavaScript files to TypeScript one at a time, retaining compatible imports and verifying the project's build after each change.
You can keep some files in JavaScript permanently if that is appropriate for the project. The goal is to improve correctness and maintainability, not to convert every file merely for the sake of using TypeScript.
10. Understanding the Limitations of checkJs
Although checkJs can identify many issues, it does not make JavaScript statically equivalent to a fully typed TypeScript application. The compiler relies on inferred types and explicit information, and some dynamic behavior cannot be verified completely.
Consider a function that receives data from an external API. Even when JSDoc describes the expected object, the real response may be malformed, incomplete, or different from what the server documentation promises.
/**
* @typedef {Object} User
* @property {number} id
* @property {string} name
*/
/**
* @param {User} user
* @returns {string}
*/
function getUserName(user) {
return user.name;
}
// A type annotation does not validate an external response.
const externalData = JSON.parse(
'{"id": 101, "name": null}'
);
console.log(getUserName(externalData));
JSON.parse returns a value that requires careful handling. A JSDoc description of User does not validate the parsed response at runtime, and the example may produce null even though the intended user name is a string.
For untrusted data, validate the actual runtime value before using it as a trusted domain object. Depending on the application, this can be done with explicit validation functions or a runtime schema-validation library.
Type checking, runtime validation, and automated tests address different concerns. Reliable applications often need all three rather than relying on any single technique.
11. Common checkJs Configuration Problems
JavaScript errors are not appearing
Verify that checkJs is enabled, allowJs is configured as needed, and the JavaScript file is part of the intended project. A file outside the configured include patterns may not be checked by the project compiler.
Too many errors appear after enabling checking
Existing JavaScript may rely on dynamic values or implicit assumptions. Review the diagnostics, add accurate JSDoc where appropriate, and adopt checking incrementally rather than suppressing all errors.
JSDoc annotations are not improving diagnostics
Confirm that the JSDoc syntax is correct, that the comments apply to the intended declaration, and that the file is being checked by the expected TypeScript configuration.
The build fails after enabling checkJs
The type-checking step may now report errors that previously went unnoticed. Resolve the diagnostics or make a deliberate, limited configuration adjustment. Keep build output settings separate from the decision to check JavaScript.
The editor and command line show different results
The editor may be using a different TypeScript version or project configuration. Check the selected TypeScript version in your editor and compare its project configuration with the one used by the command-line compiler.
Best Practices for checkJs
- Use allowJs to include JavaScript files and checkJs to enable their type diagnostics.
- Keep the include and exclude patterns aligned with the source files you intend to check.
- Use JSDoc to describe important function parameters, return values, shared models, and callback signatures.
- Review compiler diagnostics instead of suppressing them indiscriminately.
- Introduce strict checking at a pace the team can maintain.
- Run type checking regularly through a dedicated npm script or continuous integration workflow.
- Keep type-checking configuration separate from the bundler or runtime build process when appropriate.
- Validate external data at runtime when correctness and trust boundaries matter.
- Convert selected files to TypeScript when the extra type-system capabilities provide sufficient value.
Conclusion
The checkJs option makes TypeScript's static analysis available to JavaScript files. By combining allowJs, JSDoc annotations, and suitable compiler settings, developers can identify type-related problems and improve code understanding without immediately rewriting an existing application.
Use checkJs as part of a gradual improvement strategy: configure the project, examine diagnostics, document important contracts, correct errors, and introduce TypeScript where it provides practical benefits. Remember that static checks cannot validate every dynamic operation or external value, so testing and runtime validation remain important parts of reliable development.