Sub topic 7
Generic Functions with @template
This chapter assumes you can write @param and @returns tags, read JSDoc type expressions such as unions and arrays, and define types with @typedef. The examples show the types TypeScript-aware editors such as VS Code infer from JSDoc. Full type checking with // @ts-check gets its own chapter later.
The problem generics solve
Some functions work the same way whatever the type of their input. Take a function that returns the first item of an array. If you document it as @param {any[]} items and @returns {any}, the editor no longer knows that the first item of a string[] is a string. A generic function keeps that link between the input type and the output type.
The @template tag declares a type parameter. A type parameter is a placeholder name that stands for a real type, and the editor fills it in each time the function is called.
/**
* Returns the first element of an array.
* @template T
* @param {T[]} items
* @returns {T | undefined}
*/
function first(items) {
return items[0];
}
const name = first(['Ada', 'Grace']); // name: string | undefined
const count = first([3, 5, 8]); // count: number | undefined
console.log(name, count); // Ada 3How inference works
You never pass T yourself. TypeScript compares the argument you pass with the parameter's type, works out what T must be, and puts that type into the return type.
Inference only works when T appears in a parameter type. If T appears only in @returns, nothing in the call tells TypeScript what T is, so it falls back to unknown.
Multiple parameters and constraints
You can declare several type parameters, either as a comma-separated list or with one @template line each. A constraint limits which types a parameter accepts. Write it in braces before the name: @template {Constraint} Name.
/**
* Reads one property from an object.
* @template {object} T
* @template {keyof T} K
* @param {T} obj
* @param {K} key
* @returns {T[K]}
*/
function pluck(obj, key) {
return obj[key];
}
const user = { id: 'u1', age: 36 };
const age = pluck(user, 'age'); // age: number
// pluck(user, 'email'); // Error: '"email"' is not assignable to '"id" | "age"'
console.log(age); // 36Here K is constrained to keyof T, which is the union of T's property names. The return type T[K] is an indexed access type: it means "the type of property K on T".
Constraints also let you use members of the type inside the function body:
/**
* Returns the longer of two values.
* @template {{ length: number }} T
* @param {T} a
* @param {T} b
* @returns {T}
*/
function longer(a, b) {
return a.length >= b.length ? a : b;
}
console.log(longer('hello', 'hi')); // hello
console.log(longer([1, 2], [1])); // [ 1, 2 ]If you remove the constraint, a.length becomes an error, because an unconstrained T could be any type, including a number.
Defaults and generic typedefs
A type parameter can have a default, written with square brackets like an optional parameter: @template [T=unknown]. @template also works on @typedef, so you can define reusable generic shapes:
/**
* @template T
* @typedef {Object} Result
* @property {boolean} ok
* @property {T} [value]
* @property {string} [error]
*/
/**
* @param {string} text
* @returns {Result<number>}
*/
function parseCount(text) {
const n = Number(text);
return Number.isNaN(n) ? { ok: false, error: 'Not a number' } : { ok: true, value: n };
}
console.log(parseCount('42')); // { ok: true, value: 42 }Common errors
| Symptom | Cause | Fix |
|---|---|---|
| `Cannot find name 'T'` | `@template T` is missing or sits in a different comment block | Declare `@template` in the same block that uses `T` |
| Result is typed `unknown` | `T` appears only in `@returns` | Make `T` appear in at least one `@param` |
| `Property 'x' does not exist on type 'T'` | The body uses a member that the constraint does not guarantee | Add a constraint such as `@template {{ x: number }} T` |
| The jsdoc HTML tool ignores the tag | The classic jsdoc generator does not understand `@template` | Accept plain output, or use a TypeScript-aware generator |
Exercise
Write a JSDoc comment for function last(items) { return items[items.length - 1]; } so that last([true, false]) is inferred as boolean | undefined.
Show answer
Use @template T, @param {T[]} items, and @returns {T | undefined}. TypeScript matches boolean[] against T[], infers T = boolean, and returns boolean | undefined.
Exercise
A function is documented with @template T and @returns {T}, and it has a single parameter, @param {string} id. Why is the result of every call unknown, and how can a caller still get a specific type?
Show answer
T does not appear in any parameter, so nothing at the call site lets TypeScript infer it. The caller can cast the result, as in /** @type {User} */ (load('u1')). A better fix is to redesign the function so the type comes from an argument.