Course contentsShow
← JavaScript
Lesson 2614 of 2,72353. Type Safety Without TypeScriptFree lesson

Defining Custom Types with @typedef

Create reusable named types with @typedef to avoid repeating complex type definitions.

Defining Custom Types with @typedef

You'll learn how to name and reuse complex type definitions in JSDoc, eliminating repetitive type annotations.

The Problem with Repetition

Imagine you have a Person object with name, age, and email properties. If you use inline object syntax everywhere, you'll write {name: string, age: number, email: string} over and over in every @param and @type annotation. This quickly becomes tedious and error-prone.

Creating Named Types with @typedef

The @typedef tag lets you define a type once and reference it by name anywhere in your codebase:

/**
 * @typedef {Object} Person
 * @property {string} name - Full name
 * @property {number} age - Age in years
 * @property {string} email - Email address
 */

/**
 * @param {Person} user - The person to greet
 * @returns {string}
 */
function greet(user) {
  return `Hello, ${user.name}!`;
}

/**
 * @param {Person[]} people - Array of people
 * @returns {Person}
 */
function findOldest(people) {
  return people.reduce((oldest, p) => p.age > oldest.age ? p : oldest);
}

Now instead of repeating the full object shape, you just write Person. If you need to change the type definition, you update it in one place.

Why This Matters

Think of @typedef like defining a variable instead of using magic numbers everywhere. It gives complex types a meaningful name, makes your code self-documenting, and keeps type definitions consistent across your entire project.

Key Takeaway: Use @typedef to define reusable named types once, then reference them by name throughout your codebase—reducing repetition and centralizing type definitions.