JSDoc Type Annotations
In this page:
Core Concept
JSDoc type annotations let a plain JavaScript file get TypeScript's type checking and editor autocomplete without ever adopting .ts syntax, using comments like /** @type {string} */ that TypeScript's checker reads directly.
Example: Core Concept
/** @type {string} */
let name = "Ravi";
console.log(name);
Basic Setup
A basic setup needs "checkJs": true in tsconfig.json (or a per-file // @ts-check comment), after which @param, @returns, and @type tags in comments are parsed as real type information.
Example: Basic Setup
// @ts-check
/** @param {number} a @param {number} b @returns {number} */
function add(a, b) {
return a + b;
}
console.log(add(2, 3));
Typed Example
A typed example: /** @param {{name: string, age: number}} user */ function greet(user) { return 'Hi ' + user.name; } gives greet full parameter-shape checking, catching a call with a misspelled name property.
Example: Typed Example
/**
* @param {{name: string, age: number}} user
*/
function greet(user) {
return "Hi " + user.name;
}
console.log(greet({ name: "Ravi", age: 25 }));
Project Usage
In a real project, JSDoc annotations are the standard middle step for JavaScript libraries that want to ship type information to TypeScript consumers without adding a build step or rewriting their source in .ts.
Example: Project Usage
/**
* @typedef {{ id: number, name: string }} User
*/
/** @param {User} user */
function display(user) {
return `${user.id}: ${user.name}`;
}
console.log(display({ id: 1, name: "Ravi" }));
Best Practices
Use @typedef to name and reuse a complex JSDoc shape across multiple functions, instead of repeating the same inline object-type comment everywhere it's needed.
Example: Best Practices
/**
* @typedef {{ id: number, name: string }} User
*/
/** @param {User} u */
function idOf(u) { return u.id; }
/** @param {User} u */
function nameOf(u) { return u.name; }
console.log(idOf({ id: 1, name: "Ravi" }));
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: