Course contentsShow
← TypeScript
Lesson 1638 of 1,79637. Migrating JavaScript to TypeScriptFree lesson

Generic Functions with JSDoc @template

Annotate generic functions using @template to express type parameters in JavaScript without TypeScript syntax.

Generic Functions with JSDoc @template

You'll learn how to express type parameters for generic functions in plain JavaScript using JSDoc comments, bringing TypeScript-like type safety without changing your runtime code.

What Is @template?

The @template tag in JSDoc allows you to define type parameters (generics) for functions right inside JavaScript files. Think of it as labeling a "type slot" that TypeScript will fill in based on how you call the function—identical to how generic TypeScript functions work, but written as documentation comments.

This is crucial during migration because you can make your JavaScript functions type-safe without converting them to .ts files or changing any actual code syntax.

Basic Syntax

/**
 * Returns the first element of an array
 * @template T
 * @param {T[]} items - Array of items
 * @returns {T | undefined}
 */
function first(items) {
  return items[0];
}

// TypeScript infers: const num: number | undefined
const num = first([1, 2, 3]);

// TypeScript infers: const str: string | undefined
const str = first(['a', 'b', 'c']);

The @template T declares a type variable named T, which TypeScript then tracks through the function signature. When you call first([1, 2, 3]), TypeScript infers T = number automatically.

Multiple Type Parameters

/**
 * Creates a key-value pair
 * @template K, V
 * @param {K} key
 * @param {V} value
 * @returns {{key: K, value: V}}
 */
function pair(key, value) {
  return { key, value };
}

// TypeScript infers: { key: string, value: number }
const result = pair('age', 25);

Why This Matters for Migration

Imagine you have hundreds of JavaScript utility functions. Converting them all to TypeScript syntax overnight is risky and time-consuming. With @template, you can:

  • Add type safety incrementally
  • Keep existing syntax unchanged
  • Get IntelliSense and autocomplete immediately
  • Catch type errors at compile-time

Key Takeaway: @template brings generic type parameters to JavaScript files through JSDoc comments, letting you express the same type relationships as TypeScript generics without leaving .js files—perfect for gradual migration.