The Identity Generic: <T>(x: T) => T
You'll learn the simplest and most fundamental generic function pattern that returns exactly what it receives, preserving full type information.
What Is the Identity Generic?
The identity function is a function that takes a value and returns that exact same value unchanged. In TypeScript generics, the identity pattern <T>(x: T) => T means: "whatever type you pass in, that's the type I'll return."
This is the "Hello, World" of generics — the simplest possible example that demonstrates why generics exist.
The Pattern Explained
function identity<T>(x: T): T {
return x;
}
const num = identity(42); // num is type number
const str = identity("hello"); // str is type string
const bool = identity(true); // bool is type boolean
The type parameter T acts like a variable that captures whatever type you pass in. When you call identity(42), TypeScript infers T = number, so the return type becomes number. When you call identity("hello"), TypeScript infers T = string, and so on.
Why This Matters
Without generics, you'd need either:
- The unsafe
anyversion:(x: any) => any(loses all type information) - Multiple overloads for every possible type (unmaintainable)
The identity generic shows that one function can preserve all type information for infinite possible types.
Where You'll See This Pattern
The identity pattern appears in utility functions, logging wrappers, and as a building block for more complex generics. It's rarely used alone in real code, but understanding it prepares you for every generic pattern that follows.
Key Takeaway: The identity generic <T>(x: T) => T is the foundational pattern showing how a single function can preserve type information for any input type without losing specificity.