Generic Type Inference at Call Sites
You'll learn: How TypeScript automatically figures out the type arguments for generic functions based on the values you pass in.
The Magic of Automatic Inference
When you call a generic function, you could manually specify the type arguments in angle brackets, but TypeScript is smart enough to infer them from your actual arguments. This is called inference at the call site.
Remember our identity function? Here's what happens when you call it:
function identity<T>(value: T): T {
return value;
}
// TypeScript infers T as number from the argument
const num = identity(42);
// TypeScript infers T as string from the argument
const text = identity("hello");
// TypeScript infers T as boolean from the argument
const flag = identity(true);
In each case, TypeScript looks at what you passed (the number 42, the string "hello", the boolean true) and automatically determines what T should be. You don't need to write identity<number>(42) — though you could if you wanted to be explicit.
Why This Matters
This inference makes generics feel natural to use. You write code that looks like regular function calls, but you get all the type safety benefits. The type parameter flows from your argument, through the function, and into the return type automatically.
Key Takeaway: TypeScript infers generic type arguments from the values you pass to a function, eliminating the need to manually specify type parameters in most cases.