JSDoc Type Annotations in JavaScript Files
You'll learn how to add TypeScript-style type information directly to your JavaScript files using special comments, giving you type safety without converting to .ts files.
What Are JSDoc Type Annotations?
JSDoc is a documentation system that uses specially-formatted comments in JavaScript. TypeScript can read these comments and use them to type-check your JavaScript code—no conversion to .ts files required.
Think of it like putting type labels on boxes in a warehouse that only handles unlabeled boxes. The boxes themselves don't change, but now TypeScript can verify you're putting the right items in the right places.
Why This Matters for Migration
When migrating a large JavaScript codebase, you might not be ready to rename everything to .ts immediately. JSDoc annotations let you:
- Add types gradually to existing
.jsfiles - Get type-checking without changing your build process
- Document your code and get type safety simultaneously
- Test the waters before committing to full TypeScript
Basic JSDoc Type Syntax
The fundamental pattern uses @param for parameters and @returns for return types:
/**
* @param {string} name
* @param {number} age
* @returns {string}
*/
function greet(name, age) {
return `Hello ${name}, you are ${age} years old`;
}
You can also type variables directly:
/** @type {string} */
let username = "Alice";
/** @type {number[]} */
const scores = [95, 87, 92];
For objects, you can define shapes:
/**
* @param {{ id: number, name: string, active: boolean }} user
* @returns {string}
*/
function getUserStatus(user) {
return user.active ? user.name : "Inactive";
}
Union Types and Optional Parameters
JSDoc supports TypeScript's union syntax:
/**
* @param {string | number} id
* @param {boolean} [includeMetadata] - Optional parameter
* @returns {void}
*/
function logId(id, includeMetadata) {
console.log(id);
}
The square brackets around [includeMetadata] mark it as optional.
When to Use JSDoc Annotations
JSDoc annotations shine when:
- You're migrating gradually and need types now
- Your team isn't ready for full TypeScript adoption
- You want type-checking without build changes
- You're working in a mixed codebase during transition
However, once you're ready for full TypeScript, .ts files offer better ergonomics—less verbose syntax and better tooling support.
Key Takeaway: JSDoc type annotations let you bring TypeScript's type-checking to plain JavaScript files during migration, providing a zero-conversion path to gradual type safety using specially-formatted comments that TypeScript understands.