Generic Functions and Type Parameters
Generics let a function or type operate on multiple types while preserving relationships between them. A type parameter such as T is a placeholder chosen by inference or explicitly supplied by a caller. Unlike any, a generic preserves information: if a function receives a T, its result can remain T.
Introduce generics when the same logic works for multiple types and the relationship matters. Do not make every helper generic without a reason; unnecessary type parameters can make APIs harder to understand.
Preserve the input type
function identity<T>(value: T): T {
return value;
}
const textValue = identity("hello"); // string
const countValue = identity(42); // number💡 The same type parameter appears in the input and output, so the compiler preserves the relationship. The caller usually does not need to specify
T because it is inferred.Key Takeaways
- Generics preserve relationships between values and types.
- Inference often supplies generic arguments.
- Prefer useful type relationships over generic-looking code.
Knowledge Check
Why is `identity<T>(value: T): T` safer than using `any`?