Basic JSDoc Type Syntax
You'll learn how to add type safety to JavaScript files using JSDoc annotations for variables, function parameters, and return values.
What JSDoc Type Annotations Are
JSDoc is a documentation system that uses special comments in JavaScript files. When combined with TypeScript's checkJs option, these comments become type annotations that give you compile-time type checking without converting your .js files to .ts.
Think of JSDoc as "TypeScript in comments"—you write type information inside /** */ comment blocks, and the TypeScript compiler reads and enforces them just like native TypeScript syntax.
The Three Essential Tags
@type – Annotating Variables
The @type tag declares what type a variable holds:
/** @type {string} */
let username;
/** @type {number} */
const age = 42;
/** @type {boolean} */
let isActive = true;
You can also use it with complex types:
/** @type {string[]} */
const tags = [];
/** @type {{ name: string, age: number }} */
const user = { name: "Alice", age: 30 };
@param – Typing Function Parameters
The @param tag specifies the type of function parameters:
/**
* @param {string} name
* @param {number} age
*/
function greet(name, age) {
console.log(`Hello ${name}, you are ${age}`);
}
You can also add descriptions after the parameter name:
/**
* @param {string} email - The user's email address
* @param {boolean} verified - Whether the email is verified
*/
function sendEmail(email, verified) {
// implementation
}
@returns – Typing Return Values
The @returns tag (or @return) declares what a function returns:
/**
* @param {number} a
* @param {number} b
* @returns {number}
*/
function add(a, b) {
return a + b;
}
For functions that don't return anything:
/**
* @param {string} message
* @returns {void}
*/
function log(message) {
console.log(message);
}
Why This Matters
JSDoc type syntax lets you gradually add type safety to JavaScript projects without the commitment of full TypeScript conversion. You get autocomplete, error detection, and safer refactoring—all while keeping your .js files.
Key Takeaway: The @type, @param, and @returns JSDoc tags bring TypeScript-style type annotations to JavaScript files, giving you type safety through special comments that the TypeScript compiler understands.