Course contentsShow
← TypeScript
Lesson 1664 of 1,79638. Common Patterns and AntipatternsFree lesson

The Identity Function Test

If a function should return the same type it receives, you need generics not unions.

The Identity Function Test

You'll learn: Why functions that should return the exact same type they receive need generics, not unions.

The Core Problem

Here's a simple test to know if you need a generic: Does your function need to return the same type it was given?

If yes, you need a generic type parameter. A union won't cut it.

Why This Matters

Imagine you're writing a function that wraps a value in an object. If you give it a string, you want back an object containing a string. If you give it a number, you want back an object containing a number.

A union-based approach looks like this:

function wrap(value: string | number): { value: string | number } {
  return { value };
}

const result = wrap("hello");
// result is { value: string | number }
// We lost the information that it's specifically a string!

The return type is too wide. You passed in a string, but TypeScript only knows you got back string | number.

The Generic Solution

With a generic type parameter, the type flows through:

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

const result = wrap("hello");
// result is { value: string }
// The exact type is preserved!

const numResult = wrap(42);
// numResult is { value: number }

Now TypeScript preserves the specific type. The function maintains the identity of the input type.

The Mental Model

Think of generics as a type variable that gets "filled in" at the call site. Unions say "it could be any of these types mixed together." Generics say "whatever type you give me, I'll remember it and give you back that exact same type."

If your function behaves like a type-preserving container, validator, or transformer where the output type depends directly on the input type, you're looking at a generic use case.

Key Takeaway: When a function should return the same type it receives—not just "one of several possible types"—you need generics to preserve type identity through the function call.