Sub topic 8
Type Checking JavaScript with JSDoc and TypeScript
Earlier chapters used JSDoc types to describe code to people and to the jsdoc documentation tool. The TypeScript compiler can read those same comments and check your plain .js files against them. You don't rename files, add a build step, or learn new syntax. The types you already wrote are enough for the checker to find mistakes.
This chapter assumes you can write @param, @returns, @typedef, and @template tags, that you have Node.js and npm installed, and that you use an editor with TypeScript support such as VS Code. The next chapter covers sharing types across files with import(), so this one deals only with checking a file against its own annotations.
How TypeScript Reads JSDoc
The TypeScript compiler (tsc) accepts JavaScript files as input. When checking is turned on for a JavaScript file, the compiler treats JSDoc tags as type annotations:
| JSDoc tag | What TypeScript does with it |
|---|---|
| `@param {T} name` | Sets the parameter's type to `T` and makes it required unless it is written `[name]` |
| `@returns {T}` | Checks every `return` statement against `T` |
| `@type {T}` | Sets the type of a variable, property, or expression |
| `@typedef` / `@callback` | Declares a named type you can use anywhere in the file |
| `@template T` | Declares a type parameter |
| `@satisfies {T}` | Checks a value against `T` and keeps the narrower inferred type |
When there is no annotation, TypeScript infers types from the code itself. const count = 0 is a number, and an object literal gets the shape of its properties. JSDoc fills in the places where inference has nothing to work with. The main one is function parameters.
Turning On Checking for One File
The quickest way to start is a comment on the first line of a file:
// @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'.VS Code ships with TypeScript, so this works in the editor with no installation. The call greet(42) gets a red underline. Hovering over it shows error TS2345.
The checker also looks inside the function body. If the @returns tag says string but one code path returns a number, the return statement is flagged:
// @ts-check
/**
* @param {number} cents
* @returns {string}
*/
function formatCents(cents) {
if (cents < 0) {
return -1; // Error: Type 'number' is not assignable to type 'string'.
}
return `$${(cents / 100).toFixed(2)}`;
}Per-file checking suits gradual adoption. Add // @ts-check to new files and to files you are already editing, and leave the rest alone.
Checking a Whole Project with checkJs
Editor underlines only cover the files you have open. To check every file, and to fail a CI build when there are errors, install TypeScript as a development dependency and add a tsconfig.json:
npm install --save-dev typescript{
"compilerOptions": {
"allowJs": true,
"checkJs": true,
"noEmit": true
},
"include": ["src"]
}Each option does one thing:
allowJslets the compiler accept.jsfiles as input.checkJsreports type errors in those files, as if every file began with// @ts-check.noEmitstopstscfrom writing compiled output. You are using it only as a checker, and your JavaScript already runs as it is.includelimits checking to your source folder sonode_modulesand build output are skipped.
Run the check:
npx tscWith no arguments, tsc finds tsconfig.json in the current directory. It prints each error with its file, line, column, and code, and exits with a non-zero status if there are any errors. You can add it as a script in package.json so CI and teammates run the same command:
{
"scripts": {
"typecheck": "tsc"
}
}Adding strict mode
The defaults are lenient. Adding "strict": true to compilerOptions turns on a group of stricter checks. The one with the biggest effect on JavaScript code is strictNullChecks. With it on, null and undefined are no longer accepted by every type, so you must handle them explicitly:
// @ts-check
const button = document.getElementById('save');
button.addEventListener('click', () => {}); // Error under strict: 'button' is possibly 'null'.getElementById returns HTMLElement | null because the element might not exist. Without strict mode, the checker ignores the null. With strict mode, you have to narrow the type first:
// @ts-check
const button = document.getElementById('save');
if (button) {
button.addEventListener('click', () => {}); // OK: button is HTMLElement here
}Turn on strict in new projects. In an existing codebase, expect a wave of null-related errors at first. Many of them are real bugs.
Asserting Types with Casts
Sometimes you know more than the checker. getElementById returns a general HTMLElement, but you know the element is an <input> and you need its .value. In JSDoc, you assert a type by putting a @type comment directly before a parenthesized expression:
// @ts-check
const input = /** @type {HTMLInputElement} */ (document.getElementById('email'));
console.log(input.value);The parentheses are required. Without them, the comment applies to the variable declaration instead of the expression. That is a different construct, and it usually produces an error such as "Type 'HTMLElement | null' is not assignable to type 'HTMLInputElement'".
| Form | Meaning |
|---|---|
| `/** @type {T} */ const x = expr;` | Declare that `x` has type `T`, and check that `expr` is assignable to it |
| `const x = /** @type {T} */ (expr);` | Cast: treat `expr` as `T` without checking assignability |
A cast is an assertion and no check happens at runtime. If the element is missing, input is still null while the program runs, and input.value throws. Prefer narrowing with if or instanceof when the value might really be absent:
// @ts-check
const el = document.getElementById('email');
if (el instanceof HTMLInputElement) {
console.log(el.value);
}Checking a value with @satisfies
TypeScript 5.0 added @satisfies. It checks that a value matches a type but keeps the more specific type that TypeScript inferred, instead of widening the value to the declared type:
// @ts-check
/** @typedef {{ port: number, host: string }} ServerConfig */
/** @satisfies {ServerConfig} */
const config = { port: 8080, host: 'localhost' };If you misspell port or give it a string, you get an error at the definition. A plain @type would do the same, so @satisfies matters only when you want the narrower inferred type kept, for example literal values or exact key sets.
Silencing and Opting Out
Real codebases have lines the checker can't understand, such as dynamic patterns or untyped third-party code. Four directive comments control error reporting:
| Directive | Placement | Effect |
|---|---|---|
| `// @ts-check` | Top of file | Turn checking on for this file |
| `// @ts-nocheck` | Top of file | Turn checking off for this file, even with `checkJs` |
| `// @ts-ignore` | Line above the code | Suppress any error on the next line |
| `// @ts-expect-error` | Line above the code | Suppress the next line's error, and report an error if there is none |
Prefer @ts-expect-error over @ts-ignore. When someone later fixes the underlying problem, @ts-expect-error reports "Unused '@ts-expect-error' directive", which reminds you to remove it. @ts-ignore stays silently and can hide new, unrelated errors on that line.
// @ts-check
/** @param {string} s */
function shout(s) {
return s.toUpperCase();
}
// Deliberately testing bad input:
// @ts-expect-error
shout(null);Add a short reason next to each suppression so reviewers know why it is there.
Common Errors and Their Causes
Unannotated parameters are silently `any`
If a parameter has no @param type, TypeScript usually types it as any, and calls that pass the wrong value go unreported. In JavaScript files, unannotated parameters are also treated as optional, so calling the function with too few arguments is allowed. Annotations make checking useful, and leaving them out turns it off for that parameter. The ESLint rules in a later chapter can require them.
Optional parameters and `undefined`
A parameter written [taxRate] has the type number | undefined inside the function. Under strict mode, arithmetic on it is an error until you handle the undefined. If you write a default value in the code (taxRate = 0.2), TypeScript knows the parameter is a number inside the body.
Tags that the jsdoc tool accepts but TypeScript reads differently
TypeScript understands most JSDoc type syntax, including ?T for nullable, T[] and Array<T>, unions, and * for any. Some forms still behave differently in TypeScript than in the jsdoc tool. A @typedef with a typo in a type name is only a broken link in generated HTML, but TypeScript reports "Cannot find name". A typed project therefore gets stricter about type names than a docs-only project. These errors usually point at real mistakes in the documentation.
Comments not attached to code
Only /** ... */ comments placed directly before a declaration are read. A // comment, or a /* ... */ comment with a single asterisk, is ignored. The same goes for a JSDoc block separated from its function by another statement. If a type seems to have no effect, check where the comment sits first.
When to Use This Approach
JSDoc-based checking gives you most of TypeScript's checking without a compile step. Your source runs directly in Node.js or the browser, and your documentation and your types are the same text, so they can't drift apart. The trade-off is verbosity. Complex types such as conditional or mapped types are clumsy in comments, and some teams find .ts syntax easier to read once types are everywhere. A common middle path is to check .js files with JSDoc and keep complex shared types in .d.ts files. The next chapter shows how to import types across files.
Exercise
A file starts with // @ts-check and contains: const field = /* @type {HTMLInputElement} / document.querySelector('#age'); The checker reports that the type is not assignable. What is wrong, and how do you fix it?
Show answer
The cast is missing its parentheses, so the comment is read as a declaration type for field, and the declaration is then checked against querySelector's return type (Element | null), which is not assignable to HTMLInputElement. Wrap the expression: const field = /* @type {HTMLInputElement} / (document.querySelector('#age')); Better still, narrow with if (field instanceof HTMLInputElement) when the element might be missing.
Exercise
Your project has a tsconfig.json with allowJs, checkJs, and noEmit set. One legacy file, src/legacy.js, produces hundreds of errors that you can't fix this sprint. How do you exclude just that file while keeping everything else checked, and why is this better than adding @ts-ignore lines?
Show answer
Add // @ts-nocheck as the first line of src/legacy.js. It turns checking off for that file only, while checkJs keeps checking every other file. Hundreds of @ts-ignore comments would clutter the code, hide future errors on those lines, and be hard to remove later. A single file-level directive is easy to find and delete when the file is cleaned up.
Exercise
Why is // @ts-expect-error usually preferred over // @ts-ignore for suppressing a single line's error?
Show answer
@ts-expect-error itself becomes an error ("Unused '@ts-expect-error' directive") once the line no longer has an error, so stale suppressions are found and removed. @ts-ignore never reports anything, so it can stay forever and hide new, unrelated errors on that line.