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 numberType parameter inference
TypeScript infers T from the argument โ you rarely need to specify it manually:
identity("hello"); // explicit
identity("hello"); // inferred โ preferredNaming 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.
