What are Generics?
Generics are TypeScript's way of writing flexible, reusable code that works with multiple types whilst maintaining type safety. Think of them as placeholders for types that get filled in when you use the function.

Why use generics?
- Type safety - Prevent runtime errors from type mismatches
- Reusability - Write once, use with any type
- Flexibility - Work with types you haven't even thought of yet
Basic syntax
Place type parameters in angled brackets between the function name and parameters:
function myFunction<T>(param: T): T { return param; }
The <T>
is a placeholder - when you call the function, TypeScript fills in the actual type.
How it works
Generics parameterise types the same way functions parameterise values. Instead of hardcoding a specific type, you let the caller decide what type to use.
Without generics:function getFirstString(arr: string[]): string
- only works with strings
With generics:function getFirst<T>(arr: T[]): T
- works with any type whilst staying type-safe
Type inference in action
getFirst([1, 2, 3])
- TypeScript infersT
asnumber
getFirst(['a', 'b', 'c'])
- TypeScript infersT
asstring
getFirst([true, false])
- TypeScript infersT
asboolean
Common conventions
T
- Most common generic type name (short for "Type")K
- Often used for key typesV
- Often used for value types- Use descriptive names for complex scenarios:
<User>
,<ApiResponse>
Practical benefits
Instead of writing separate functions for each type or using any
(which loses type safety), generics let you write one function that adapts to whatever type you throw at it whilst keeping all the TypeScript benefits.