TypeScript
/Intermediate
Generic Functions
Definition
Functions that can operate over a variety of types rather than a single one, while still preserving perfect type safety. They use a type variable (usually `<T>`) to capture the type passed by the user.
Explain Like I'm New
A generic function is a template. Imagine a machine that wraps gifts. You don't build a machine for wrapping Books, and a separate machine for wrapping Toys. You build ONE Generic machine, and you tell it 'Whatever type of item goes IN, that exact same type of item comes OUT'.
Real World Example
The `useState<T>()` hook in React. It accepts any type you pass it, and returns an array containing that exact same type.
Common Use Cases
- •Reusable utility functions
- •Array manipulation functions like `.map()`
Interactive Example
// BAD: We lose type safety (returns 'any') function wrapAny(item: any): any { return { value: item }; } // GOOD: The generic <T> links the input type to the output type function wrapItem<T>(item: T): { value: T } { return { value: item }; } // TS infers T is string. Returns { value: string } const wrappedString = wrapItem("Alice"); // TS infers T is number. Returns { value: number } const wrappedNumber = wrapItem(100); // Multiple generics! function mergePairs<K, V>(key: K, value: V) { return { key, value }; }
Interview Questions
basic
- What does the `<T>` stand for in Generics?
intermediate
- Do you always have to explicitly write `<string>` when calling a generic function?
advanced
- Can a generic function have multiple type variables?