Sub topic 3
Let JavaScript and TypeScript coexist with allowJs and checkJs
Assume you know modern JavaScript, can run Node.js and npm commands, and understand that static types describe values before the program runs. This chapter uses a gradual migration: existing .js files continue working while new or converted files use TypeScript.
Configure the compiler
TypeScript normally reads .ts files. The allowJs option also lets it include .js files in the project. This allows both file types to appear under the same src directory.
The checkJs option asks TypeScript to report type errors in JavaScript files. It does not convert those files into TypeScript. It checks them while preserving JavaScript syntax.
Install TypeScript and create a configuration file:
npm install --save-dev typescript @types/node
npx tsc --initReplace the generated configuration with a small migration-friendly version:
{
"compilerOptions": {
"target": "ES2020",
"module": "commonjs",
"rootDir": "src",
"outDir": "dist",
"allowJs": true,
"checkJs": true,
"esModuleInterop": true,
"skipLibCheck": true,
"strict": false
},
"include": ["src"]
}rootDir identifies the source directory. outDir identifies the generated JavaScript directory. The compiler can now read both src/app.js and src/app.ts.
Control checking per file
With checkJs: true, every included JavaScript file is checked. This can reveal many errors at once in a large codebase. You can temporarily exclude a file with // @ts-nocheck, but use that only as a short-lived migration marker.
You can instead leave checkJs off and opt into checking one file:
// @ts-check
/**
* @param {{ name: string, age: number }} user
* @returns {string}
*/
function formatUser(user) {
return user.name.toUpperCase() + " (" + user.age + ")";
}
console.log(formatUser({ name: "Ada", age: 36 }));The // @ts-check comment applies to that JavaScript file. The JSDoc comments describe the parameter object and the returned string. TypeScript can then report an incorrect call, such as a missing age property.
This per-file approach is useful when you want to migrate a few stable modules first. Project-wide checkJs is useful when you want consistent checking across the remaining JavaScript code.
A practical migration sequence
Use this order for a mixed project:
- Add
tsconfig.jsonwithallowJsand a suitableincludepath. - Compile the existing project to discover configuration problems.
- Enable
checkJsglobally, or add// @ts-checkto selected files. - Fix errors in one module at a time.
- Rename a prepared
.jsfile to.tswhen its JavaScript assumptions are explicit.
The compiler output becomes a migration checklist. Do not treat every warning as a reason to rewrite the whole application.
Exercise
What is the difference between allowJs and checkJs?
Show answer
allowJs includes JavaScript files in the TypeScript project, while checkJs asks TypeScript to type-check those JavaScript files.