Generic Functions in TypeScript
From the TypeScript cheat sheet · Generics · verified Jul 2026
Generic Functions
Create reusable functions that work with multiple types
typescript
// Generic function
function identity<T>(value: T): T {
return value
}
// Using generic function
const num = identity<number>(42)
const str = identity<string>("hello")
const auto = identity(true) // Type inference
// Generic with arrays
function first<T>(array: T[]): T | undefined {
return array[0]
}
// Multiple type parameters
function pair<T, U>(first: T, second: U): [T, U] {
return [first, second]
}💡 TypeScript often infers generic types automatically
📌 Use constraints to limit generic types
✅ Generics make code reusable and type-safe