Concept Explanation
Imagine a "Box." If you build a box only for "Apples," you can't put "Oranges" in it. A Generic is like a "Magic Box." When you put an object in, the box becomes a box for that type of object.
Generics allow you to write functions and classes that work with any type while still being 100% safe.
Syntax or Core Structure
A Generic Function
// The <T> is a placeholder for "Type"
function wrapInArray<T>(item: T): T[] {
return [item];
}
const numArr = wrapInArray(10); // TS knows this is number[]
const strArr = wrapInArray("Hi"); // TS knows this is string[]
Common Mistakes
- Over-Genericizing: Don't use a generic if a simple union (
string | number) will work. Generics are for when the input and output types must match. - Naming Confusion: The letter
Tis standard, but you can name it anything:<UserType>. - Constraints: If you need a generic to have a specific property (like
.length), you must useextends:<T extends { length: number }>.
Practice Exercises
- The Identity Function: Write a generic function
identity<T>(val: T): Tthat simply returns the value it received. - The List Swapper: Write a generic function that takes an array of two items and swaps their positions.
- The API Wrapper: Research a generic
ApiResponse<T>type. How would it help you handle different data (Users, Posts, Comments) from the same fetch function?