Generics
Generics let you write reusable code that works with different types. Instead of writing the same function for strings and for numbers, you write it once with a generic type. Think of generics like a template: fill in the type when you use it.
// Without generics: only works with numbers
function getFirst(arr: number[]): number {
return arr[0]
}
// With generics: works with any type
function getFirst<T>(arr: T[]): T {
return arr[0]
}
getFirst<number>([1, 2, 3]) // 1
getFirst<string>(["a", "b"]) // "a"