← Back to TypeScript Course | Chapter 27: Migration from JavaScript | Lesson 4 of 6

JSDoc Type Annotations

JSDoc comments can add type information to JavaScript files. This provides useful checking while keeping the files as JavaScript.

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

typescript
/** @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

typescript
// @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

typescript
/**
 * @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

typescript
/**
 * @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

typescript
/**
 * @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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.