Syntax
function name<T>(param: T): T { }Examples
A Generic Function
A function that works with any type, while TypeScript still tracks exactly which type was used.
function identity<T>(value: T): T {
return value;
}
const num = identity(42); // T is inferred as number, returns number
const str = identity("hello"); // T is inferred as string, returns string
// Without generics, you would need "any" (losing type safety)
// or separate functions for each type (losing reusability)Generics with Arrays
A common, practical use: a function that works with an array of any type.
function getFirstElement<T>(arr: T[]): T | undefined {
return arr[0];
}
const firstNum = getFirstElement([1, 2, 3]); // inferred as: number | undefined
const firstName = getFirstElement(["Alice", "Bob"]); // inferred as: string | undefinedBest practices
- Use generics instead of any when a function or class should work with multiple types while still preserving type safety and autocomplete
- Let TypeScript infer the generic type argument from the actual arguments passed, rather than always specifying it explicitly (identity<string>("hi") is rarely needed)
- Use descriptive generic names (TItem, TResponse) instead of just T for complex functions with multiple type parameters, to keep signatures readable
- Reach for generics specifically when a function's behavior genuinely does not depend on the specific type - if it does, a union type or overloads may fit better
Runtime & versions
Compiled to JavaScript. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
TypeScript Handbook