The Identity Function Problem
You'll learn: Why a simple function that returns its input creates a typing challenge that reveals the need for generics.
The Problem
Imagine you want to write a function that takes any value and returns it unchanged — an identity function. Sounds trivial, right?
function identity(value: any): any {
return value;
}
const num = identity(42); // num is type 'any'
const text = identity("hello"); // text is type 'any'
This works, but we've lost all type safety. TypeScript can't tell us that num is a number or that text is a string. We're back to the wild west of any.
The Type-Specific Trap
You might try writing separate functions:
function identityNumber(value: number): number {
return value;
}
function identityString(value: string): string {
return value;
}
This is type-safe, but absurd. You'd need infinite functions for every possible type — numbers, strings, objects, arrays, custom types... It's unmaintainable.
The Core Challenge
The identity function needs to express: "Whatever type you give me, I'll give you back that exact same type." But with the tools you've learned so far (primitives, unions, type aliases, any), there's no way to create this relationship between input and output types.
This is the gap that generics exist to fill.
Key Takeaway: The identity function problem shows that sometimes you need a function's return type to depend on its input type — a relationship that basic type annotations can't express.