Course contentsShow
← TypeScript
Lesson 609 of 1,79614. Generics in PracticeFree lesson

The Identity Function Pattern

Learn the simplest generic pattern that preserves input type information through function calls.

The Identity Function Pattern

You'll learn the simplest and most foundational generic pattern that returns exactly what you give it, preserving type information perfectly.

What Is the Identity Function?

The identity function is a function that returns its input unchanged. In plain JavaScript, it looks like this:

function identity(value) {
  return value;
}

Simple enough — but without types, we lose all information about what we passed in. TypeScript's generic version solves this beautifully:

function identity<T>(value: T): T {
  return value;
}

Why This Pattern Matters

This pattern is the building block of generic programming. It teaches you that:

  1. Type parameters flow through: Whatever type T is at the call site becomes the return type
  2. No information is lost: Unlike using any, the type is preserved exactly
  3. The compiler infers perfectly: You rarely need to specify T manually

The Pattern in Action

const num = identity(42);        // num: number
const str = identity("hello");   // str: string
const bool = identity(true);     // bool: boolean
const arr = identity([1, 2, 3]); // arr: number[]

Notice how each call preserves the exact type. The function acts like a type mirror — it reflects back precisely what you gave it.

Think of It Like a Tunnel

Imagine a tunnel where you send something through one end and it comes out the other side unchanged. The identity function is a typed tunnel — it remembers what kind of thing went in and guarantees that's what comes out.

Key Takeaway: The identity function pattern <T>(value: T) => T is the simplest generic: it preserves the exact input type through the function call, demonstrating how type parameters flow from input to output without losing precision.