Generics: The Reusable Templates

Generics: The Reusable Templates in JavaScript: Imagine a "Box." If you build a box only for "Apples," you can't put "Oranges" in it.

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

  1. 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.
  2. Naming Confusion: The letter T is standard, but you can name it anything: <UserType>.
  3. Constraints: If you need a generic to have a specific property (like .length), you must use extends: <T extends { length: number }>.

Practice Exercises

  1. The Identity Function: Write a generic function identity<T>(val: T): T that simply returns the value it received.
  2. The List Swapper: Write a generic function that takes an array of two items and swaps their positions.
  3. 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?