Sub topic 3
Writing Types in JSDoc
This chapter assumes you can write JavaScript functions and objects. It also assumes you have read the earlier chapters on comment blocks and on @param and @returns. Here we cover what goes inside the curly braces: the type expression.
The working model
A type expression is the text between { and } in a tag such as @param {string} name. Two tools read it. The jsdoc tool prints it in generated docs. TypeScript uses it for checking and editor hints. Most syntax works in both tools, but TypeScript is stricter and supports more forms. If you write types that TypeScript accepts, both tools will usually understand you.
Common type forms
| Form | Example | Meaning | Column |
|---|---|---|---|
| Primitive | `{string}`, `{number}`, `{boolean}` | A single primitive type | |
| Union | `{string \ | number}` | Either type |
| Array | `{string[]}` or `{Array<string>}` | Array of strings | |
| Object literal | `{{ id: string, age: number }}` | Object with these properties | |
| Record | `{Object<string, number>}` | Keys are strings, values are numbers | |
| Nullable | `{?string}` or `{string \ | null}` | String or null |
| Any | `{*}` or `{any}` | No checking | |
| Function | `{function(string): boolean}` | Takes a string, returns a boolean | |
| Literal | `{'asc' \ | 'desc'}` | Exactly one of these strings |
Note the doubled braces in the object literal row. The outer pair delimits the type expression, and the inner pair is the object type itself.
A worked example
/**
* Sorts and formats a list of scores.
* @param {number[]} scores - Raw scores.
* @param {'asc' | 'desc'} order - Sort direction.
* @param {{ prefix: string, decimals?: number }} options - Formatting options.
* @param {?string} label - Optional heading, or null for none.
* @returns {string[]} Formatted lines.
*/
function formatScores(scores, order, options, label) {
const sorted = [...scores].sort((a, b) => (order === 'asc' ? a - b : b - a));
const lines = sorted.map(
(s) => `${options.prefix}${s.toFixed(options.decimals ?? 0)}`
);
return label === null ? lines : [label, ...lines];
}
console.log(formatScores([3.14, 9.5, 1], 'desc', { prefix: '- ', decimals: 1 }, 'Scores'));
// [ 'Scores', '- 9.5', '- 3.1', '- 1.0' ]Inside an object literal type, decimals?: number marks one property as optional. This is the TypeScript form. The bracket form [name] applies to whole parameters, not to properties inside an inline object type.
Common errors
Other mistakes come up often:
- Using bare
{Object}or{Array}. These say nothing about the contents. Write{string[]}or an object literal type instead. - Confusing nullable and optional.
{?string}means the value may benull.[label]or{string=}means the argument may be left out, so its value isundefined. These are different cases. - Unescaped pipes in tables and Markdown. Inside code this is not a problem, but a doc generator may render
|strangely in descriptions. Keep unions inside the braces. - Overusing
{*}. It turns off checking. Use{unknown}when you truly don't know the type. TypeScript will then make callers narrow the value before using it. - Inline object types repeated everywhere. Once a shape appears twice, name it. The next chapter shows how with
@typedef.
Exercises
Exercise
Write a @param tag for a parameter id that can be a string or a number, or can be null.
Show answer
@param {string | number | null} id. The form {?(string|number)} is equivalent.
Exercise
What is the difference between @param {?number} limit and @param {number} [limit]?
Show answer
{?number} means callers must pass the argument, but it can be null. [limit] means callers can omit the argument, in which case it is undefined.
Exercise
Write a type for an object whose keys are user IDs (strings) and whose values are arrays of tag strings.
Show answer
{Object<string, string[]>}. In TypeScript-aware tools, {Record<string, string[]>} also works.