Course contentsShow
← TypeScript
Lesson 537 of 1,79613. GenericsFree lesson

What Are Generic Functions?

Functions that work with multiple types by introducing type parameters, providing flexibility without losing type safety.

What Are Generic Functions?

You'll learn how to write a single function that works safely with multiple types instead of duplicating code or losing type safety.

The Core Idea

A generic function is a function that uses type parameters to work with different types while preserving full type information. Instead of writing separate functions for strings, numbers, and objects—or resorting to any—you write one function that adapts to whatever type you pass in.

Think of it like a universal adapter: the same physical device works with different plugs by adjusting its shape to match what you insert. Generic functions adjust their types based on what you "insert" (pass as arguments).

How It Works

When you declare a generic function, you introduce a type parameter (conventionally named T, U, etc.) that acts as a placeholder. TypeScript infers the actual type from your function call:

function wrap<T>(value: T): T[] {
  return [value];
}

const numberArray = wrap(42);        // T inferred as number
const stringArray = wrap("hello");   // T inferred as string

The type parameter T "captures" the type you provide and flows through the function's signature. You get autocomplete, type checking, and safety—all without hardcoding specific types.

Why This Matters

Generic functions let you build flexible, reusable utilities that don't sacrifice type information. You avoid code duplication and the danger zone of any, while TypeScript ensures the inputs and outputs stay consistent.

Key Takeaway: Generic functions use type parameters to create flexible, type-safe code that adapts to different types without losing the benefits of static typing.