Course contentsShow
← JavaScript
Lesson 2619 of 2,72353. Type Safety Without TypeScriptFree lesson

Template Types with @template

Define generic type parameters with @template for flexible, reusable type definitions.

Template Types with @template

What you'll learn: How to create flexible, reusable JSDoc type definitions that work with multiple types using @template.

What Are Template Types?

In JSDoc, @template lets you define generic type parameters—placeholders that represent "any type the caller provides." This is JavaScript's answer to generics in TypeScript, allowing you to write functions and types that adapt to whatever data they receive while maintaining type safety.

Think of @template like a variable for types: instead of hardcoding "this function returns a number," you say "this function returns whatever type you give it."

Basic Syntax

/**
 * @template T
 * @param {T} value
 * @returns {T}
 */
function identity(value) {
  return value;
}

// JSDoc understands: string in → string out
const result = identity("hello");

The T acts as a type placeholder. When you call identity("hello"), JSDoc infers T is string, so it knows the return type is also string.

Multiple Type Parameters

/**
 * @template K, V
 * @param {K} key
 * @param {V} value
 * @returns {{key: K, value: V}}
 */
function makePair(key, value) {
  return { key, value };
}

const pair = makePair(42, "answer");
// JSDoc knows: {key: number, value: string}

With Type Constraints

You can specify what types T must extend:

/**
 * @template {string | number} T
 * @param {T} input
 * @returns {T}
 */
function restrictedIdentity(input) {
  return input;
}

Key Takeaway: @template defines generic type parameters in JSDoc, enabling you to write flexible, type-safe functions and types that preserve the relationship between input and output types without hardcoding specific types.