Sub topic 4
Reusable Types with @typedef and @callback
When the same object shape shows up in five function signatures, writing it out inline five times is tedious, and the copies drift apart. JSDoc lets you name a type once and refer to it everywhere. This chapter covers @typedef for object shapes, @property for their fields, and @callback for function signatures, plus the mistakes that commonly break them.
This chapter assumes you can already write @param and @returns tags and know the basic type expression syntax: unions like string|number, arrays like string[], and optional parameters in square brackets. Both were covered in earlier chapters.
Why Name a Type
Consider a function that takes a user object. Without a named type, you either describe the object loosely as {Object}, which tells the reader nothing, or you spell out its full shape inline:
/**
* @param {{id: string, name: string, email?: string}} user
* @returns {string}
*/
function label(user) {
return `${user.name} <${user.email ?? 'no email'}>`;
}That works for one function. Once saveUser, findUser, and filterUsers all need the same shape, you have four copies to keep in sync, and none of them gives you a place to describe what each field means. A named type fixes both problems.
Defining Object Shapes with @typedef and @property
A @typedef block declares a new type name. The type in braces is the base type, and each @property line adds one field with its own type and description.
/**
* A registered user of the application.
* @typedef {Object} User
* @property {string} id - Unique identifier.
* @property {string} name - Display name.
* @property {string} [email] - Optional email address.
* @property {'admin'|'member'} [role='member'] - Access level.
*/
/**
* Builds a display label for a user.
* @param {User} user
* @returns {string}
*/
function label(user) {
return `${user.name} <${user.email ?? 'no email'}>`;
}
/** @type {User} */
const ada = { id: 'u1', name: 'Ada' };
console.log(label(ada)); // Ada <no email>Some details matter here:
{Object}and{object}are both accepted. TypeScript treats them the same inside a@typedef.- Square brackets around a property name make it optional, the same as for
@param. [role='member']records a default value, but that default is only documentation. Nothing in JavaScript fills it in. Your code still has to apply the default itself, for example withuser.role ?? 'member'.- The text before the tags is the description of the type. Documentation generators show it, and editors show it on hover.
Nested properties
When a property is itself an object, you can describe its fields with dotted names:
/**
* @typedef {Object} Order
* @property {string} id
* @property {Object} shipping - Where the order is sent.
* @property {string} shipping.city
* @property {string} shipping.postcode
* @property {number[]} itemIds
*/This works, but nesting more than one level gets hard to read. If shipping appears in other places, give it its own typedef, Address, and write @property {Address} shipping.
The inline form
You can also write the whole shape as a type literal inside the braces:
/** @typedef {{ x: number, y: number }} Point */
/**
* @param {Point} a
* @param {Point} b
* @returns {number}
*/
function distance(a, b) {
return Math.hypot(a.x - b.x, a.y - b.y);
}
console.log(distance({ x: 0, y: 0 }, { x: 3, y: 4 })); // 5The inline form is compact and suits small, obvious shapes. The @property form lets you write a description for each field, and the jsdoc HTML generator renders those descriptions as a table. Use @property when the fields need explaining.
Aliasing non-object types
@typedef is not limited to objects. Any type expression can get a name:
/** @typedef {'pending'|'paid'|'refunded'} PaymentStatus */
/** @typedef {string|number} Id */Naming a string-literal union like PaymentStatus is a cheap way to give an enum-like set of values a single definition.
Describing Function Shapes with @callback
Functions that take other functions, such as predicates, comparators, and event handlers, need a way to describe the function argument. @callback declares a named function type. Its @param and @returns tags describe the callback's own signature, not the signature of the function that accepts it.
/**
* @typedef {Object} User
* @property {string} id
* @property {string} name
* @property {boolean} active
*/
/**
* Decides whether a user should be kept.
* @callback UserPredicate
* @param {User} user - The user being tested.
* @param {number} index - Position in the source array.
* @returns {boolean} True to keep the user.
*/
/**
* Returns the users that match a predicate.
* @param {User[]} users
* @param {UserPredicate} predicate
* @returns {User[]}
*/
function filterUsers(users, predicate) {
return users.filter(predicate);
}
/** @type {User[]} */
const users = [
{ id: 'u1', name: 'Ada', active: true },
{ id: 'u2', name: 'Lin', active: false },
];
console.log(filterUsers(users, (u) => u.active).map((u) => u.name)); // [ 'Ada' ]When an editor with TypeScript support reads this, the arrow function (u) => u.active gets u inferred as User, so autocomplete works inside the callback without any annotation there.
@callback versus a function type expression
You can also express a function type directly in a @typedef. Two syntaxes are common:
/** @typedef {function(User, number): boolean} UserPredicateClosure */
/** @typedef {(user: User, index: number) => boolean} UserPredicateArrow */| Form | Per-parameter descriptions | Understood by TypeScript | Understood by the jsdoc HTML tool |
|---|---|---|---|
| `@callback` block | Yes | Yes | Yes |
| `function(User): boolean` (Closure syntax) | No | Yes | Yes |
| `(user: User) => boolean` (TypeScript syntax) | No | Yes | No, it causes a parse error |
The arrow form is the most familiar if you write TypeScript, but the classic jsdoc generator's type parser does not accept it. If you generate HTML docs with jsdoc, use @callback or the Closure form. If your comments are only for editors and type checking, any of the three works. @callback is the most readable choice whenever the parameters need explanation.
Documenting Options Objects Without a Typedef
Sometimes an object shape belongs to one function only, such as an options parameter. You can describe its fields with dotted @param names instead of creating a typedef:
/**
* Fetches a resource with retries.
* @param {string} url - Address to fetch.
* @param {Object} [options] - Request settings.
* @param {number} [options.retries=3] - Attempts before giving up.
* @param {number} [options.timeoutMs=5000] - Per-attempt timeout.
* @returns {Promise<Response>}
*/
async function fetchWithRetry(url, { retries = 3, timeoutMs = 5000 } = {}) {
let lastError;
for (let attempt = 0; attempt < retries; attempt++) {
try {
return await fetch(url, { signal: AbortSignal.timeout(timeoutMs) });
} catch (err) {
lastError = err;
}
}
throw lastError;
}The parent @param {Object} [options] line must come first, and each child name must start with the parent's exact name. This also works for destructured parameters. The name options is yours to choose, because a destructured parameter has no name in the source.
As a rule of thumb, use dotted @param names for a shape used by one function and a @typedef for a shape used by two or more.
Where Typedefs Live and Who Can See Them
A typedef is not attached to any code, so its visibility depends on the file it sits in and the tool reading it.
| Context | Visibility of a `@typedef` |
|---|---|
| TypeScript, file with no `import` or `export` (a script) | Global: every other script file in the project sees it |
| TypeScript, file with `import` or `export` (a module) | Exported from that module. Other files must import it |
| jsdoc HTML tool, no `@module` tag | Listed as a global type |
| jsdoc HTML tool, file with `@module` tag | Scoped to the module, shown as `module:name~User` |
Inside an ES module, you bring a typedef from another file in with an import() type expression. The chapter "Sharing Types Across Files" covers that in detail. For now, know that defining a typedef inside a module does not leak it into the global namespace, and that two script files defining the same global name will collide.
Common Errors
Merging a typedef into a function's comment
/**
* @typedef {Object} Range
* @property {number} min
* @property {number} max
* @param {Range} r
* @returns {number}
*/
function span(r) {
return r.max - r.min;
}This looks reasonable but fails in confusing ways. The jsdoc tool treats the whole block as the typedef, so span disappears from the generated docs. TypeScript may still type r, but the comment no longer reads clearly as either thing. Give each typedef its own /** ... */ block, separate from the function's comment.
Orphaned @property tags
@property lines without a preceding @typedef in the same block do nothing for an ordinary function. If you meant to document an options parameter, use dotted @param names.
Mismatched dotted names
Writing @param {number} [opts.retries] when the parent parameter is named options produces a warning from the jsdoc tool, and TypeScript ignores the field. The prefix must match the parent's name exactly.
Expecting `@property` defaults to apply
As noted above, [role='member'] documents a default. It does not create one. Under type checking, user.role is still typed 'admin'|'member'|undefined, which is a useful reminder to handle the missing case.
Treating optional as "may be undefined"
With TypeScript's exactOptionalPropertyTypes option on, [email] means the key may be absent, not that it may hold undefined. If callers pass { email: undefined }, declare the property as {string|undefined} [email].
Putting It Together
This runnable file defines a status alias, two object types, and a callback type, then uses all of them:
/** @typedef {'todo'|'doing'|'done'} TaskStatus */
/**
* A unit of work on the board.
* @typedef {Object} Task
* @property {string} id - Unique identifier.
* @property {string} title - Short summary.
* @property {TaskStatus} status - Current workflow state.
* @property {string[]} [tags] - Free-form labels.
*/
/**
* Tasks grouped by status.
* @typedef {Object} Board
* @property {Task[]} todo
* @property {Task[]} doing
* @property {Task[]} done
*/
/**
* Called once for every task that changes status.
* @callback StatusListener
* @param {Task} task - The task after the change.
* @param {TaskStatus} previous - Status before the change.
* @returns {void}
*/
/**
* Groups tasks into a board.
* @param {Task[]} tasks
* @returns {Board}
*/
function toBoard(tasks) {
/** @type {Board} */
const board = { todo: [], doing: [], done: [] };
for (const task of tasks) board[task.status].push(task);
return board;
}
/**
* Moves a task to a new status and notifies a listener.
* @param {Task} task
* @param {TaskStatus} next
* @param {StatusListener} onChange
* @returns {Task}
*/
function move(task, next, onChange) {
const previous = task.status;
const updated = { ...task, status: next };
if (previous !== next) onChange(updated, previous);
return updated;
}
/** @type {Task[]} */
const tasks = [
{ id: 't1', title: 'Write docs', status: 'todo' },
{ id: 't2', title: 'Review PR', status: 'doing', tags: ['urgent'] },
];
const moved = move(tasks[0], 'done', (t, prev) =>
console.log(`${t.title}: ${prev} -> ${t.status}`)
);
console.log(toBoard([moved, tasks[1]]).done.length); // 1Running it with node prints Write docs: todo -> done and then 1. In an editor with type checking on, passing 'finished' as the status argument is flagged, because TaskStatus allows only the three listed values.
Exercise
Write a @callback named Comparator for a function that takes two Task objects, a and b, and returns a number (negative if a sorts first). Then document a function sortTasks(tasks, compare) that uses it and returns a new sorted array.
Show answer
/ Orders two tasks. @callback Comparator @param {Task} a - First task. @param {Task} b - Second task. @returns {number} Negative if a comes first, positive if b comes first, 0 if equal. / / Returns a sorted copy of the tasks. @param {Task[]} tasks @param {Comparator} compare @returns {Task[]} */ function sortTasks(tasks, compare) { return [...tasks].sort(compare); }
Exercise
A function createServer(options) reads options.port (a number, default 8080) and options.host (a string, optional). Only this one function uses the shape. How should you document options, and why?
Show answer
Use dotted @param names, because the shape belongs to a single function: @param {Object} [options], @param {number} [options.port=8080], @param {string} [options.host]. A @typedef is worth creating only when two or more functions share the shape. The function body must still apply the 8080 default itself.
Exercise
A teammate writes one comment block that contains @typedef {Object} Config, two @property lines, and then @param {Config} cfg, placed directly above function load(cfg). The generated HTML docs show Config but no load function. What went wrong and how do you fix it?
Show answer
The jsdoc tool treated the whole block as the Config typedef doclet, so it never documented load. Move the @typedef and @property lines into their own /* ... / block, and leave a separate block above load containing only its description, @param {Config} cfg, and @returns.