Sub topic 3
Let JavaScript and TypeScript coexist with allowJs and checkJs
This chapter assumes you have Node.js and npm installed, a working tsconfig.json from the previous chapter, and a working knowledge of modern JavaScript. You do not need to know TypeScript syntax yet. The chapter covers how to let .js and .ts files live in one project, and how to get type feedback on JavaScript before you rename anything.
Why coexistence matters
A real codebase rarely converts in one commit. If you rename every file at once, you get hundreds of errors, a huge pull request, and a team that cannot ship in the meantime. TypeScript has two compiler options and one comment that avoid this:
allowJslets the compiler accept.jsfiles as part of the program.checkJsmakes the compiler report type errors in those.jsfiles.// @ts-checkturns on that checking for a single file, withoutcheckJs.
With these, you can move through three states for each file: plain JavaScript, JavaScript checked by the compiler, and finally TypeScript.
You can skip the middle state for small files. For large or risky files, it lets you find problems while the file still runs exactly as before.
Turn on allowJs
The configuration from the previous chapter already contains allowJs:
{
"compilerOptions": {
"target": "ES2020",
"module": "commonjs",
"rootDir": "src",
"outDir": "dist",
"allowJs": true,
"esModuleInterop": true,
"skipLibCheck": true,
"strict": false
},
"include": ["src"]
}With allowJs: true, three things change:
- A
.tsfile can import a.jsfile, and the compiler resolves the import. - The compiler reads
.jsfiles inincludeand emits them tooutDir, so your build output contains both kinds of file in one place. - The compiler infers types from the JavaScript code and from JSDoc comments, which lets TypeScript callers see them.
Notice what allowJs does not do. It does not report type errors in your JavaScript. It only parses the files, so syntax the compiler cannot read still fails. Type checking is a separate switch.
Make the compiler read the right files
The include array decides which files join the program. "include": ["src"] picks up every supported file under src, including .js, .ts, and .tsx. If you keep JavaScript outside src, for example in scripts/, those files are not part of the build, and importing them from src raises an error because they sit outside rootDir.
Keep outDir outside include. If the compiled dist/ folder were inside an included folder, the compiler would treat generated .js files as input. TypeScript excludes outDir by default, but the setting is easy to break if you add an explicit exclude array. If you write one, list dist and node_modules yourself.
Check JavaScript with checkJs
To get type errors in all JavaScript files, add checkJs:
{
"compilerOptions": {
"allowJs": true,
"checkJs": true,
"noEmit": true
},
"include": ["src"]
}checkJs applies the type checker to every .js file in the program. On a large legacy project this can produce hundreds of errors in one run. The compiler has to guess types from untyped code, and it reports every place the guess is wrong or missing.
Because of that, checkJs is better as a late step than as a first one. For most projects the better approach is to check files one at a time.
Check one file with @ts-check
Put // @ts-check on the first line of a JavaScript file. The compiler then checks that file only, and the rest of the project stays untouched.
// @ts-check
/**
* @param {{ name: string, age: number }} user
* @returns {string}
*/
function formatUser(user) {
return user.name.toUpperCase() + " (" + user.age + ")";
}The JSDoc comment is how you give types to JavaScript. @param describes a parameter and @returns describes the return value. The compiler reads the types inside the braces. Now a bad call is an error:
// @ts-check
/**
* @param {{ name: string, age: number }} user
* @returns {string}
*/
function formatUser(user) {
return user.name.toUpperCase() + " (" + user.age + ")";
}
formatUser({ name: "Ada" });
// Error: Property 'age' is missing in type '{ name: string; }'
// but required in type '{ name: string; age: number; }'.The file still runs under Node as plain JavaScript. A JSDoc comment is only a comment to the JavaScript engine. That is the main benefit of this stage: you get checking with no change in runtime behavior.
Where the errors show up
Your editor shows the errors as you type, because the editor uses the same language service as tsc. To see the errors from the command line, run the compiler without emitting files:
npx tsc --noEmit--noEmit runs the type check and writes nothing. This is useful in the early stages, when you want feedback but your existing build still produces the output.
Opt a file out with @ts-nocheck
If you enabled checkJs globally, you can exclude files that are not ready:
// @ts-nocheckAt the top of a file, this turns off checking for that file. You can also silence a single line with // @ts-ignore or // @ts-expect-error. Prefer @ts-expect-error. It reports an error if the line below it stops being an error, so stale suppressions do not pile up.
A migration workflow using these tools
A workable order, with allowJs on and checkJs off:
- Pick a file with few dependencies, such as a utility module.
- Add
// @ts-checkto the top. - Run
npx tsc --noEmitand read the errors. - Fix real bugs, and add JSDoc types where the compiler cannot infer them.
- Commit. The file is now checked but still JavaScript.
- When you are ready, rename it to
.ts(covered in the next chapter) and convert the JSDoc types into annotations.
Once most files carry @ts-check or are already .ts, turn on checkJs globally and add // @ts-nocheck to the few stragglers.
Common problems
| Symptom | Likely cause | Fix |
|---|---|---|
| No errors in a `.js` file that is clearly wrong | `checkJs` is off and the file has no `// @ts-check` | Add the comment or enable `checkJs` |
| `Cannot find module './util'` from a `.ts` file importing JS | `allowJs` is off, or the file is outside `include` | Set `allowJs: true` and check `include` |
| Error that a file is not under `rootDir` | JavaScript sits outside `src` | Move it, or change `rootDir` |
| `Cannot write file ... would overwrite input file` | Output folder overlaps the input files | Set `outDir` and exclude it |
| Everything typed as `any` in imported JavaScript | No JSDoc and nothing to infer from | Add JSDoc on the exported functions |
What the compiler infers from JavaScript
Even without JSDoc, the compiler infers types from how code is written. A function that returns a + b has inferred parameters of type any, because nothing says what a and b are. The inference works well for object literals, constants, and the results of built-in functions. It works poorly for function parameters. That is why parameter JSDoc gives the most value.
Some JavaScript patterns are loose in ways that TypeScript flags under checkJs:
- Properties added to an object after creation, such as
config.debug = trueon an object literal that did not declaredebug. - Functions called with fewer arguments than they declare. In JavaScript every parameter is optional, but TypeScript requires each one unless you mark it optional with
[name]in JSDoc. - Values that are sometimes
nullorundefined, which matter oncestrictNullChecksis on.
Mark an optional parameter in JSDoc with brackets:
// @ts-check
/**
* @param {string} name
* @param {number} [age] Optional age in years
* @returns {string}
*/
function describe(name, age) {
return age === undefined ? name : name + " (" + age + ")";
}
describe("Ada");
describe("Ada", 36);Exercises
Exercise
A project has allowJs: true and checkJs: false. One file, src/price.js, starts with // @ts-check. Another file, src/legacy.js, has no comment. Which files does npx tsc --noEmit report type errors for, and why?
Show answer
Only src/price.js. The // @ts-check comment turns checking on for that file. checkJs is off, so src/legacy.js is parsed and included in the program but not type checked.
Exercise
You add // @ts-check to a file and the compiler reports Property 'age' is missing. You are sure the call site is correct and plan to add // @ts-ignore above it. Which comment is the better choice, and why?
Show answer
// @ts-expect-error with a short reason. It also suppresses the error, but if the error later disappears (for example after you fix the types), the compiler reports the unused suppression, so you can remove it. @ts-ignore stays silently forever.
Exercise
Write the JSDoc comment for function area(width, height) that returns a number, where height is optional.
Show answer
/* @param {number} width @param {number} [height] @returns {number} */