Advertisement
Beginner TypeScript, Generics

What problem do generics solve compared to using 'any' for a reusable function?

Short answer

'any' disables type checking entirely, losing all safety and autocomplete. Generics let a function or type work with MULTIPLE specific types while preserving the actual relationship between input and output types — the compiler still knows exactly what type comes out based on…

Save TypeScript mock interview
Advertisement
AModel answer
'any' disables type checking entirely, losing all safety and autocomplete. Generics let a function or type work with MULTIPLE specific types while preserving the actual relationship between input and output types — the compiler still knows exactly what type comes out based on what type went in.
function identity<T>(value: T): T {
  return value;
}
const a = identity('hello'); // inferred as string, not any
const b = identity(42);      // inferred as number, not any
Real-world example
Writing a single reusable getFirst() function that correctly preserves the specific array element type for any array passed in.
Likely follow-ups
  • How does the compiler determine what T is when you call a generic function without explicitly specifying it?
Related topics