Generic Functions: Type Parameters
Add type parameters to functions for reusability.
Welcome
Generics allow you to write functions that work with any type while preserving type safety. Instead of using `any`, you use a type parameter that is resolved when the function is called.
The Problem Generics Solve
A function returning `any` loses type information. Generics preserve the relationship between input and output types.
// Without generics — loses type info
function first(arr: any[]): any { return arr[0]; }
// With generics — type-safe
function first<T>(arr: T[]): T { return arr[0]; }All lessons in this course
- Generic Functions: Type Parameters
- Generic Interfaces and Type Aliases
- Generic Constraints with extends
- Default Type Parameters