Sub topic 7
Generic Functions with @template
Some functions work the same way no matter what type of data they get. A function that returns the first element of an array doesn't care whether the array holds numbers, strings, or User objects. If you type its parameter as any[] and its return as any, you lose the link between input and output. Callers get back a value their editor knows nothing about. The @template tag fixes this. It declares a type parameter, a placeholder for a type, and the editor fills it in at each call site.
This chapter assumes you have read the earlier chapters on @param, @returns, type expressions, and @typedef/@callback. It also assumes you can read basic TypeScript-style type syntax such as T[], A | B, and { key: Type }. Type checking with // @ts-check and checkJs gets its own chapter later. Here you only need to know that VS Code and other TypeScript-aware editors read @template to power hover types, autocompletion, and error squiggles.
Why `any` Is Not Enough
Compare two versions of the same function:
/**
* Returns the first element of an array.
* @param {any[]} items
* @returns {any}
*/
function firstLoose(items) {
return items[0];
}
/**
* Returns the first element of an array.
* @template T
* @param {T[]} items
* @returns {T | undefined}
*/
function first(items) {
return items[0];
}
const a = firstLoose(['x', 'y']); // a: any
const b = first(['x', 'y']); // b: string | undefinedThe two functions behave identically at runtime. The difference is only in what tools know about them. With firstLoose, the editor gives up: a.toUpperCase() and a.notARealMethod() both look fine. With first, the editor knows b is a string or undefined, so it offers string methods and warns that b might be undefined.
@template T says "this function has a type parameter called T." Each time you write T in the same comment, it refers to the same unknown type. At the call site, the type checker works out what T is from the arguments.
How Inference Works at the Call Site
You never write the type argument yourself in JavaScript. JavaScript has no first<string>(...) syntax. The checker infers it instead.
The checker compares each argument with the parameter type that mentions T, collects candidate types, and picks one. It then substitutes that type into the return type and into any other parameter types. This is why a type parameter should appear in at least one parameter. If T only appears in @returns, there is nothing to infer from, and T ends up as unknown. The generic adds nothing in that case.
Multiple Type Parameters
You can declare several type parameters with commas, or with one @template tag per parameter. Both forms mean the same thing.
/**
* Groups items by a key computed from each item.
* @template T, K
* @param {T[]} items - The items to group.
* @param {(item: T) => K} keyFn - Computes the group key for an item.
* @returns {Map<K, T[]>} A map from each key to the items with that key.
*/
function groupBy(items, keyFn) {
const groups = new Map();
for (const item of items) {
const key = keyFn(item);
const group = groups.get(key);
if (group) {
group.push(item);
} else {
groups.set(key, [item]);
}
}
return groups;
}
const words = ['apple', 'avocado', 'banana'];
const byLetter = groupBy(words, (w) => w[0]);
// byLetter: Map<string, string[]>
console.log(byLetter.get('a')); // [ 'apple', 'avocado' ]Here T is inferred from items and K from the return type of keyFn. Inside the callback, w is already typed as string, because the checker fixed T from the first argument before it looked at the arrow function.
Constraining a Type Parameter
An unconstrained T can be anything, so inside the function you can't assume it has any properties. To require a shape, put a type in braces before the parameter name. The type parameter then accepts only types assignable to that constraint.
/**
* Returns whichever argument is longer.
* @template {{ length: number }} T
* @param {T} a
* @param {T} b
* @returns {T}
*/
function longer(a, b) {
return a.length >= b.length ? a : b;
}
longer('hello', 'hi'); // string
longer([1, 2, 3], [4]); // number[]
// longer(10, 20); // Error under type checking: number has no 'length'The constraint does two jobs. It lets the body use a.length safely, and it rejects calls with types that lack length. The return type stays specific: passing strings gives back a string, not just { length: number }.
Constraining with `keyof`
A common pattern ties one type parameter to the keys of another:
/**
* Extracts one property from every object in an array.
* @template T
* @template {keyof T} K
* @param {T[]} items
* @param {K} key
* @returns {T[K][]}
*/
function pluck(items, key) {
return items.map((item) => item[key]);
}
const users = [
{ id: 'u1', age: 31 },
{ id: 'u2', age: 27 },
];
const ages = pluck(users, 'age'); // number[]
const ids = pluck(users, 'id'); // string[]
// pluck(users, 'email'); // Error: '"email"' is not assignable to '"id" | "age"'
console.log(ages, ids);keyof T is the union of T's property names, and T[K] is the type of the property at key K. The editor autocompletes 'id' and 'age' as you type the second argument. This shows why the two parameters are declared in separate tags: the constraint on K refers to T, so T must be declared first.
Literal Inference
A constraint also changes how specific the inferred type is. Without a constraint, first(['a']) infers T as string. With @template {string} T and an argument 'a', the checker keeps the literal type 'a'. This is useful when a function returns exactly the key or tag it was given, for example an event name used later in a lookup.
Generic Type Definitions
@template also works with @typedef and @callback. Put it in the same comment block as the definition, and the type takes type arguments where you use it.
/**
* The outcome of an operation that can fail.
* @template T
* @typedef {{ ok: true, value: T } | { ok: false, error: string }} Result
*/
/**
* Parses a base-10 integer without throwing.
* @param {string} text
* @returns {Result<number>}
*/
function parseIntSafe(text) {
const n = Number.parseInt(text, 10);
return Number.isNaN(n)
? { ok: false, error: `Not a number: ${text}` }
: { ok: true, value: n };
}
const r = parseIntSafe('42');
if (r.ok) {
console.log(r.value + 1); // r.value: number
} else {
console.log(r.error);
}Checking r.ok narrows the union, so r.value is only available on the success branch.
A generic @callback works the same way:
/**
* @template T, U
* @callback Mapper
* @param {T} item
* @param {number} index
* @returns {U}
*/
/**
* Maps an array, skipping results that are null or undefined.
* @template T, U
* @param {T[]} items
* @param {Mapper<T, U | null | undefined>} fn
* @returns {U[]}
*/
function mapDefined(items, fn) {
/** @type {U[]} */
const out = [];
items.forEach((item, i) => {
const value = fn(item, i);
if (value !== null && value !== undefined) out.push(value);
});
return out;
}
console.log(mapDefined(['1', 'x', '3'], (s) => {
const n = Number(s);
return Number.isNaN(n) ? null : n;
})); // [ 1, 3 ]Notice /** @type {U[]} */ inside the function body. Type parameters are in scope for the whole function, so inline type annotations can use them. Without that annotation, out would be typed as any[] and the return type would be checked less strictly.
Generic Classes
Put @template in the comment above a class, and every member can use the type parameter.
/**
* A last-in, first-out stack.
* @template T
*/
export class Stack {
constructor() {
/** @type {T[]} */
this.items = [];
}
/** @param {T} item */
push(item) {
this.items.push(item);
}
/** @returns {T | undefined} */
pop() {
return this.items.pop();
}
}
/** @type {Stack<number>} */
const numbers = new Stack();
numbers.push(1);
// numbers.push('two'); // Error: string is not assignable to numberThe constructor takes no arguments, so the checker has nothing to infer T from. Annotate the variable with /** @type {Stack<number>} */ to supply the type argument. If the constructor took a T parameter, for example an initial item, inference would work as it does for functions.
Supplying Type Arguments Without `<...>`
Since JavaScript can't pass type arguments at a call, you steer inference in other ways:
| Situation | Technique | Example |
|---|---|---|
| Variable holding a generic instance | Annotate the variable | `/** @type {Stack<string>} */ const s = new Stack();` |
| Empty array argument | Cast the argument | `first(/** @type {string[]} */ ([]))` |
| Inferred type too wide or too narrow | Annotate the result or the argument | `/** @type {Result<number>} */ const r = ...` |
| Repeated use of one instantiation | Define an alias | `/** @typedef {Result<User>} UserResult */` |
A JSDoc cast needs the parentheses around the expression: /** @type {X} */ (expr). Without them, the comment is read as an ordinary annotation and no cast happens.
Default Type Parameters
Recent TypeScript versions accept a default in square brackets: @template [T=string]. The default applies when you use a generic typedef or class without type arguments, for example writing Box instead of Box<number>. Defaults are less common in plain JavaScript code. Check your TypeScript version before relying on them.
Common Mistakes
| Mistake | What happens | Fix |
|---|---|---|
| `@template` in a different comment from `@param` | `T` is unknown; editor reports "Cannot find name 'T'" | Keep all tags in one `/** ... */` block |
| `@template {string} K, V` expecting both constrained | Only `K` gets the constraint | Use separate tags: `@template {string} K` and `@template {string} V` |
| Constraint referring to a later parameter | `keyof T` fails if `T` is declared afterward | Declare `T` before `K` |
| `T` used only in `@returns` | Nothing to infer; result is `unknown` | Add `T` to a parameter, or drop the generic |
| Calling `first<string>(x)` | Syntax error in JavaScript | Annotate or cast instead |
| Expecting the jsdoc HTML generator to show type parameters | jsdoc doesn't treat `@template` as a standard tag, so the HTML output ignores it | Mention type parameters in the description if the HTML docs matter |
When to Reach for a Generic
Use @template when the output type depends on the input type: containers, collection helpers, wrappers such as Result, and functions that return one of their arguments. Avoid it when a union or a concrete type says the same thing more simply. A function that accepts string | number and always returns string doesn't need a type parameter. If you're unsure, write the call sites first and check what callers need to know about the return value.
Exercise
Write a JSDoc-annotated function last that returns the last element of an array, typed so that last([1, 2, 3]) is number | undefined and last(['a']) is string | undefined.
Show answer
/* Returns the last element of an array. @template T @param {T[]} items @returns {T | undefined} / function last(items) { return items[items.length - 1]; }
Exercise
A teammate writes @template {object} T, K above a function and then uses @param {K} key with @returns {T[K]}. The editor reports an error on T[K]. Why, and how do you fix it?
Show answer
In a comma list, the braces constraint applies only to the first type parameter, so K is unconstrained and the checker can't prove it is a key of T. Declare them separately: @template {object} T followed by @template {keyof T} K.
Exercise
Given the generic Stack class in this chapter, why does const s = new Stack(); s.push(1); give weaker type checking than the annotated version, and what are two ways to fix it?
Show answer
The constructor has no parameter that mentions T, so the checker can't infer T and falls back to a loose type. Fix it by annotating the variable (/** @type {Stack<number>} */ const s = new Stack();) or by changing the constructor to accept an initial T value (for example @param {T[]} [initial]) so that T can be inferred from the argument.