Sub topic 8
Type Checking JavaScript with JSDoc and TypeScript
This chapter assumes you can write JSDoc type expressions and @typedef blocks, which earlier chapters covered. It also assumes you can run npm and npx and use an editor such as VS Code. The goal is to turn your JSDoc comments from documentation into types that a tool checks.
The working model
TypeScript's compiler can read plain .js files. When checking is on, it treats JSDoc tags such as @param, @returns, @type, and @typedef as type annotations. Your code stays JavaScript: no build step, no .ts files, and nothing changes at runtime. The checker only reports problems.
TypeScript gives you two places to see those reports:
- The editor. VS Code ships with the TypeScript language service. It shows red squiggles and IntelliSense as you type.
- The command line.
tscchecks the whole project, which suits CI.
Checking one file with // @ts-check
To check a single file, put // @ts-check at the top. It needs no configuration.
// @ts-check
/**
* @param {string} name
* @returns {string}
*/
function greet(name) {
return `Hello, ${name}`;
}
greet(42); // Error: Argument of type 'number' is not assignable to parameter of type 'string'.The code still runs and prints Hello, 42. The error appears only in a TypeScript-aware editor. This lets you adopt checking one file at a time.
Checking a whole project with checkJs
For a project, install TypeScript and add a tsconfig.json:
npm install --save-dev typescript{
"compilerOptions": {
"allowJs": true,
"checkJs": true,
"noEmit": true
},
"include": ["src"]
}| Option | Effect |
|---|---|
| `allowJs` | Lets the compiler include `.js` files |
| `checkJs` | Reports type errors in those files, like `// @ts-check` on every file |
| `noEmit` | Checks only and writes no output files |
| `include` | Limits checking to `src` |
Run the check:
npx tscIf there are no errors, tsc prints nothing and exits with code 0. Any error gives a non-zero exit code, so CI fails the build.
You can add "strict": true for stricter checks. The most useful part of it is strictNullChecks, which forces you to handle null and undefined before using a value.
Opting out and suppressing errors
Some files or lines need exceptions:
// @ts-nocheckat the top of a file turns checking off for that file, even whencheckJsis on.// @ts-expect-erroron the line before an error suppresses it. If the error later goes away, TypeScript reports the directive itself as unused.// @ts-ignoresuppresses the next line's error without any warning when the error disappears.
Type casts in JSDoc
Sometimes you know more than the checker does. For example, document.getElementById returns HTMLElement | null, but you know the element is an input. To cast, put a @type comment directly before a parenthesized expression:
// @ts-check
const input = /** @type {HTMLInputElement} */ (document.getElementById('email'));
console.log(input.value);Common errors
| Symptom | Cause | Fix |
|---|---|---|
| Cast has no effect | Parentheses missing around the expression | Write `/** @type {T} */ (expr)` |
| Comment types are ignored | Comment starts with `/*` or `//` | JSDoc must start with `/**` |
| Optional argument flagged as missing | Parameter not marked optional | Use `[name]` or `{T=}` in `@param` |
| `Object is possibly 'null'` | `strictNullChecks` is on | Add a null check or a cast |
| `tsc` checks nothing | `.js` files not in `include`, or `allowJs` is off | Fix `tsconfig.json` |
| Parameter silently typed `any` | No `@param` type given | Add a JSDoc type |
Exercise
A file has // @ts-check at the top. This line produces no error, but el.value is reported as not existing on type HTMLElement: const el = /** @type {HTMLInputElement} */ document.querySelector('#q');. Why, and how do you fix it?
Show answer
The cast applies only when the expression it targets is wrapped in parentheses. Without them, TypeScript ignores the @type comment, so the variable keeps the inferred type from querySelector. Write const el = /** @type {HTMLInputElement} */ (document.querySelector('#q'));.
Exercise
Your team wants CI to fail on JSDoc type errors in every file under src, without generating any output files. Which tsconfig.json options do you need, and what command does CI run?
Show answer
Set allowJs: true, checkJs: true, and noEmit: true, with "include": ["src"]. CI runs npx tsc. It exits with a non-zero code when any error is found.