Sub topic 3
Writing Types in JSDoc
The previous chapter used simple types such as {number} and {string} inside @param and @returns. Real code also passes arrays, objects, values that may be null, callbacks, and parameters that accept more than one kind of value. This chapter covers the type expression syntax that goes between the curly braces. It explains how to write each common shape, how the two dialects of the syntax differ, and which mistakes cause wrong documentation or wrong editor hints without any warning.
This chapter assumes you can write JavaScript functions and objects, and that you know the basic @param and @returns tags from the previous chapter. You do not need to know TypeScript. Some TypeScript-flavored syntax appears below because editors and type checkers read it.
Where Type Expressions Live
A type expression is the text inside the curly braces of a tag. The same syntax works in every tag that takes a type:
/**
* @param {string | number} id - The record ID.
* @returns {Promise<string[]>} The matching names.
*/
async function lookup(id) {
return [String(id)];
}
/** @type {Map<string, number>} */
const scores = new Map();The @type tag annotates a variable, constant, or property directly. You will use it often for values that are not function parameters.
Two kinds of tools read these expressions, and they do not accept exactly the same syntax:
- The jsdoc documentation generator uses the Closure Compiler type syntax. It mostly copies the expression into the HTML output and links known type names.
- TypeScript, which powers IntelliSense in VS Code and the
checkJsmode covered later, accepts almost all Closure syntax and also accepts TypeScript's own type syntax.
In practice, most teams write the subset that both tools understand and use TypeScript-only forms when editor checking matters more than the generated HTML.
Primitive and Built-in Types
Use the lowercase names for primitive values:
| Type expression | Meaning |
|---|---|
| `{string}` | A string primitive |
| `{number}` | A number, including `NaN` and `Infinity` |
| `{boolean}` | `true` or `false` |
| `{bigint}` | A BigInt such as `10n` |
| `{symbol}` | A Symbol |
| `{undefined}` | The value `undefined` |
| `{null}` | The value `null` |
| `{object}` | Any non-primitive value |
| `{Date}`, `{RegExp}`, `{Error}` | Instances of built-in classes |
| `{*}` or `{any}` | Any value, with no checking |
| `{unknown}` | Any value, which must be narrowed before use (TypeScript) |
Union Types
A union says the value can be one of several types. Separate the members with |:
/**
* Formats an ID for display.
* @param {string | number} id
* @returns {string}
*/
function formatId(id) {
return typeof id === "number" ? `#${id}` : id;
}The original Closure syntax requires parentheses around a union, as in {(string|number)}. Both tools accept unions with or without parentheses. You still need parentheses when a union is combined with array syntax, which is covered next.
TypeScript also accepts literal types. A literal type allows only a specific value, and literal types are often combined into a union:
/**
* @param {"asc" | "desc"} direction
* @returns {number[]}
*/
function sortNumbers(direction) {
const values = [3, 1, 2];
return values.sort((a, b) => (direction === "asc" ? a - b : b - a));
}The jsdoc generator prints literal unions as text. The editor, however, offers "asc" and "desc" as completions and flags "up" as an error when checking is on.
Arrays and Tuples
An array type can be written in two equivalent ways:
/** @type {string[]} */
const tags = ["js", "docs"];
/** @type {Array<string>} */
const moreTags = ["jsdoc"];
/** @type {Array.<string>} */ // older Closure form, still valid
const legacyTags = ["closure"];The bracket suffix binds tighter than |. This rule causes a common bug:
/** @type {string | number[]} */ // a string, OR an array of numbers
const a = "x";
/** @type {(string | number)[]} */ // an array whose items are strings or numbers
const b = ["x", 1];
/** @type {Array<string | number>} */ // same as b, often easier to read
const c = ["y", 2];TypeScript also understands tuples, which are arrays with a fixed length and a type for each position:
/**
* Splits "key=value" into a pair.
* @param {string} entry
* @returns {[string, string]}
*/
function splitPair(entry) {
const index = entry.indexOf("=");
return [entry.slice(0, index), entry.slice(index + 1)];
}Object Types
For a small object with known properties, write a record type inline:
/**
* @param {{ x: number, y: number }} point
* @returns {number} Distance from the origin.
*/
function length(point) {
return Math.hypot(point.x, point.y);
}TypeScript accepts either commas or semicolons between properties. An optional property can be marked with ? in TypeScript syntax:
/**
* @param {{ host: string, port?: number }} options
* @returns {string}
*/
function toUrl(options) {
return `http://${options.host}:${options.port ?? 80}`;
}Inline object types become hard to read after three or four properties, or when you need the same shape in several places. The next chapter introduces @typedef for those cases.
Dictionaries
When the keys are not known in advance, describe the object as a map from key type to value type:
/** @type {Object.<string, number>} */ // Closure form
const wordCounts = { the: 12, a: 7 };
/** @type {Record<string, number>} */ // TypeScript utility type
const visits = { home: 3 };
/** @type {{ [key: string]: number }} */ // TypeScript index signature
const prices = { apple: 1.25 };All three describe the same shape for the editor. Only Object.<string, number> is native Closure syntax. The jsdoc generator still displays the other two as text.
Nullable, Non-Nullable, and Optional
The Closure syntax has prefix operators for null:
{?string}meansstringornull.{!Date}means aDatethat is nevernull.
TypeScript reads ?string as string | null. It ignores ! because types are non-nullable by default when strictNullChecks is on. Without strictNullChecks, TypeScript lets null and undefined into every type, so neither marker changes much.
Many developers find the explicit union clearer:
/**
* Finds a user's nickname.
* @param {string} id
* @returns {string | null} The nickname, or null if none is set.
*/
function findNickname(id) {
return id === "1" ? "Ace" : null;
}Nullable and optional mean different things. Nullable means the value can be null. Optional means the value can be missing, which in JavaScript makes it undefined. For parameters, mark optional values with square brackets around the name, as shown in the previous chapter. The Closure postfix = form, {string=}, means the same thing:
/**
* @param {string} name
* @param {string} [title] - Optional: may be undefined.
* @param {?string} middleName - Required, but may be null.
* @returns {string}
*/
function fullName(name, title, middleName) {
return [title, name, middleName].filter(Boolean).join(" ");
}Function Types
A parameter or variable that holds a function needs a function type. There are two syntaxes:
/**
* Applies a transform to every number.
* @param {number[]} values
* @param {function(number): number} fn - Closure syntax
* @returns {number[]}
*/
function mapAll(values, fn) {
return values.map(fn);
}
/**
* Runs a callback once for each index.
* @param {number} count
* @param {(index: number) => void} callback - TypeScript arrow syntax
* @returns {void}
*/
function times(count, callback) {
for (let i = 0; i < count; i++) callback(i);
}
mapAll([1, 2], (n) => n * 2);
times(3, (i) => console.log(i));The arrow syntax lets you name parameters, which makes the editor's hints easier to read. The Closure syntax is understood by both tools. Avoid the bare {Function} type. It accepts any function and tells readers nothing about the arguments or the return value.
Async functions return promises, so give the resolved type as a type argument:
/**
* @param {string} url
* @returns {Promise<string>} The response body.
*/
async function fetchText(url) {
const response = await fetch(url);
return response.text();
}Write Promise<string>, not string. TypeScript reports an error if an async function is annotated with a non-promise return type.
Generic Built-ins
Built-in container types take type arguments in angle brackets:
| Expression | Meaning |
|---|---|
| `Promise<number>` | A promise that resolves to a number |
| `Map<string, User>` | A map from string keys to `User` values |
| `Set<number>` | A set of numbers |
| `Array<string>` | Same as `string[]` |
| `Iterable<string>` | Anything usable with `for...of` that yields strings |
| `ReadonlyArray<number>` | An array the function promises not to modify (TypeScript) |
Using Iterable<T> instead of T[] for an input is a deliberate choice. It tells callers they may pass a Set, a generator, or an array. Writing your own generic functions is covered in the chapter on @template.
Common Errors and How to Spot Them
| Mistake | Effect | Fix | Column | Column |
|---|---|---|---|---|
| `{String}` instead of `{string}` | Documents wrapper objects | Use lowercase primitive names | ||
| `{string \ | number[]}` when you meant an array of either | Wrong precedence | `{(string \ | number)[]}` |
| `{Object}` or `{Function}` | Almost no information or checking | Use an inline object type or function signature | ||
| `{array}` or `{int}` | Unknown names; TypeScript treats them as `any` or reports them | `{Array<T>}`, `{number}` | ||
| Missing braces: `@param string name` | jsdoc reads `string` as the parameter name | `@param {string} name` | ||
| `@returns {string}` on an `async` function | Type error under checking | `@returns {Promise<string>}` | ||
| `{?T}` used to mean "optional" | Means "may be null" | Use `[name]` or `{T=}` |
The quickest way to catch these mistakes is to hover over the function name in VS Code. The editor shows the signature it inferred from your comment. If a parameter shows up as any, the type expression was not understood.
Choosing a Form
Whatever form you choose, add | null or mark the parameter optional when the value can be absent.
Exercises
Exercise
Write a @param type for a parameter rows that is an array where each item is either a string or null.
Show answer
@param {(string | null)[]} rows or equivalently @param {Array<string | null>} rows. Without the parentheses, {string | null[]} means "a string, or an array of nulls."
Exercise
A function loadConfig(path) is declared async and resolves to an object with a required name string and an optional numeric retries. Write its @returns tag.
Show answer
@returns {Promise<{ name: string, retries?: number }>}. The outer Promise<...> is required because async functions always return a promise.
Exercise
What is the difference between @param {?number} limit and @param {number} [limit]?
Show answer
{?number} means the caller must pass the argument, but its value may be null. [limit] means the caller may leave the argument out, so its value may be undefined.
Exercise
Annotate a constant handlers that maps event names (strings) to functions taking an Event and returning nothing.
Show answer
/** @type {Record<string, (event: Event) => void>} */ const handlers = {}; The Closure form {Object.<string, function(Event): void>} is also valid.