Course contentsShow
← TypeScript
Lesson 1605 of 1,79637. Migrating JavaScript to TypeScriptFree lesson

JSDoc Comments as Type Annotations

Use JSDoc syntax in JavaScript files to provide type information that TypeScript can understand and check.

JSDoc Comments as Type Annotations

You'll learn: How to add TypeScript type information to JavaScript files using JSDoc comment syntax, enabling type-checking without converting to .ts.

What JSDoc Type Annotations Are

When migrating a large JavaScript codebase to TypeScript, converting every file at once isn't always practical. JSDoc comments offer a middle ground: you can add type information directly in your JavaScript files using specially-formatted comments that TypeScript understands.

Think of JSDoc as writing type annotations in the margins of your JavaScript book rather than rewriting the book in a new language. The JavaScript remains unchanged and runs identically, but TypeScript can read your "margin notes" to provide type safety.

How JSDoc Type Annotations Work

You place type information inside /** ... */ comments using @ tags. TypeScript's compiler reads these annotations when checkJs is enabled:

/**
 * @param {string} name - The user's name
 * @param {number} age - The user's age
 * @returns {string} A greeting message
 */
function greet(name, age) {
  return `Hello ${name}, you are ${age} years old`;
}

// TypeScript catches this error:
greet(42, "thirty"); // Error: Arguments are swapped

Common JSDoc Patterns

You can express most TypeScript concepts through JSDoc:

/** @type {string} */
let username;

/** @type {string | null} */
let maybeUser = null;

/** @type {{ id: number, name: string }} */
const user = { id: 1, name: "Alice" };

/** @type {Array<number>} */
const scores = [95, 87, 92];

When This Matters During Migration

JSDoc annotations are invaluable when:

  • You have a massive JavaScript codebase
  • You want type safety now without rewriting
  • Some team members aren't ready for TypeScript syntax
  • You need to validate third-party JavaScript modules

You get immediate type-checking benefits while keeping valid JavaScript that runs anywhere.

Key Takeaway: JSDoc comments let you annotate JavaScript with type information that TypeScript can check, providing a gradual on-ramp to full type safety without changing your runtime code or file extensions.