Skip to content

Generic

Medium — good to knowGeneral Dev

ELI5 — The Vibe Check

A generic is like a recipe that works for any ingredient. Instead of writing a 'sort apples' function AND a 'sort oranges' function, you write one 'sort anything' function and just tell it what you're sorting when you use it.

Real Talk

Generics allow you to write reusable code that works with multiple types while preserving type safety. You define a function or class with a type parameter (like T) that gets filled in at usage time, avoiding the need for duplicated type-specific implementations.

Show Me The Code

// TypeScript generic function
function first<T>(arr: T[]): T {
  return arr[0];
}

first<number>([1, 2, 3]); // returns number
first<string>(["a", "b"]); // returns string

When You'll Hear This

"Make that utility function generic so it works with any type." / "The API returns a generic response wrapper."

Made with passive-aggressive love by manoga.digital. Powered by Claude.