JSDoc for Object Shapes and Interfaces
What you'll learn: How to define reusable, complex object types in JavaScript files using @typedef for better type safety without TypeScript.
The Problem: Inline Types Get Messy
When you're working in JavaScript with JSDoc type annotations, simple types like @param {string} work fine. But what happens when you need to describe complex objects with multiple properties? Writing the entire shape inline becomes unreadable:
/**
* @param {{name: string, age: number, address: {street: string, city: string}}} user
*/
function greetUser(user) {
console.log(`Hello, ${user.name}!`);
}
That's cluttered and hard to maintain. Worse, if you need this same shape in multiple places, you're copying and pasting that massive type annotation everywhere.
The Solution: @typedef for Type Definitions
The @typedef tag lets you define a named type once and reuse it throughout your JavaScript file (or even across files). Think of it as creating an interface in TypeScript, but written as a JSDoc comment:
/**
* @typedef {Object} User
* @property {string} name - The user's full name
* @property {number} age - The user's age in years
* @property {Address} address - The user's home address
*/
/**
* @typedef {Object} Address
* @property {string} street
* @property {string} city
*/
/**
* @param {User} user
*/
function greetUser(user) {
console.log(`Hello, ${user.name} from ${user.address.city}!`);
}
Now when checkJs is enabled or you use @ts-check, TypeScript understands the shape of User and provides autocomplete and error checking—without converting to .ts.
Why This Matters
@typedef gives you a single source of truth. Change the User definition once, and all functions using it instantly reflect that change. You get documentation and type safety together, making gradual migration smoother.
Key Takeaway: Use @typedef to define complex object types in JavaScript files, creating reusable, maintainable type definitions that work just like TypeScript interfaces—all within JSDoc comments.