GenericsLesson 4.1
What are generics in TypeScript and why do you need them
generic type parameter, identity function, type parameter naming, generic vs any, generic inference, basic syntax
The problem generics solve
Without generics, a function that works with multiple types must use any, losing all type safety:
function identity(value: any): any { return value; }
const result = identity("hello"); // result is any, not stringWith generics, the type is captured and returned:
function identity(value: T): T { return value; }
const result = identity("hello"); // result is string
const num = identity(42); // num is number Type parameter inference
The compiler infers T from the argument, so you can usually leave it unspecified:
identity("hello"); // explicit
identity("hello"); // inferred - preferred Naming conventions
Single letters are conventional: T for a general type, K for key, V for value, E for element. For clarity in complex generics, use descriptive names like TItem or TPayload.
Think of T as a variable for a type. The function does not care what type it holds - it guarantees only that input and output types match.
