Sub topic 3
Type Checking JavaScript with JSDoc and TypeScript
This chapter assumes you can already write JSDoc blocks with @param, @returns, and @typedef, that you know ES modules, and that you can run npx commands.
Type Checking with // @ts-check and checkJs
TypeScript can read JSDoc types in plain .js files. If you add // @ts-check as the first line of a file, a TypeScript-aware editor such as VS Code reports type errors in that 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'.To check a whole project, for example in CI, set checkJs in tsconfig.json and run npx tsc:
{
"compilerOptions": {
"allowJs": true,
"checkJs": true,
"noEmit": true
},
"include": ["src"]
}noEmit tells TypeScript to check the files without writing any output. Your source stays plain JavaScript.
Sharing Types Across Files
A @typedef belongs to the file it is defined in. To reuse it in another file, reference it with an import() type expression:
/** @typedef {import('./user.js').User} User */
/**
* @param {User} user
* @returns {string}
*/
export function describe(user) {
return `${user.name} (${user.id})`;
}Generating a Documentation Site
The same comments can produce HTML documentation:
npm install --save-dev jsdoc
npx jsdoc src -r -d docsThe -r flag recurses into subdirectories, and -d sets the output folder.
Enforcing JSDoc with ESLint
eslint-plugin-jsdoc catches missing tags, mismatched parameter names, and malformed types:
// eslint.config.js
import jsdoc from 'eslint-plugin-jsdoc';
export default [
jsdoc.configs['flat/recommended'],
];What to Document and Keeping It Accurate
- Document every exported function, class, and type. These form your public contract.
- Describe intent, units, and edge cases. Leave out details the code already makes obvious.
- When you change a signature, update the comment in the same commit.
checkJsand the linter will flag many mismatches, but they cannot check whether your descriptions are still true.
Exercise
Your project has checkJs: true, but {import('./types.js').Order} reports that Order cannot be found, even though types.js defines it with @typedef. What is the likely cause, and how do you fix it?
Show answer
types.js has no import or export, so TypeScript treats it as a script and its typedefs are global rather than exported. Add an export (for example export {};) so the file becomes a module.