How Type Parameters Flow Through Code
You'll learn: How a single type parameter connects input types to output types throughout a function, creating a "type thread" that ties everything together.
The Core Idea
When you use a type parameter like <T>, it acts like a variable for types—not values. TypeScript captures the actual type at the call site and then uses that same type throughout the entire function. This creates a connection: whatever type goes in must be the type that comes out.
Think of it like a conveyor belt in a factory. If you put red boxes on the belt at the start, the same red boxes flow through each station and come out at the end. The type parameter is the "color" that flows through your code.
Following the Flow
function identity<T>(value: T): T {
return value;
}
const result = identity(42);
// T flows: number → parameter → return → number
Here's what happens:
- You call
identity(42) - TypeScript sees
42is anumber - TypeScript sets
T = numberfor this call - The parameter becomes
value: number - The return type becomes
number resultis inferred asnumber
The type parameter creates a contract: the return type must match the input type. This is why generics are so powerful—they preserve the relationship between types across your function's body.
Multiple References, Same Type
function pair<T>(first: T, second: T): T[] {
return [first, second];
}
Both first and second must be the same type T, and the array returned contains that same type. The type parameter flows through all three positions.
Key Takeaway: Type parameters create a "type thread" that connects inputs to outputs, ensuring type consistency flows through every part of your function where that parameter appears.