Welcome back! I am Mihir, and in this lesson we will learn generic functions in TypeScript.
A generic function uses type parameters to work with different types safely.
Basic Generic Function
function wrap<T>(value: T): T[] {
return [value];
}
const numbers = wrap(10);
const names = wrap("Mihir");TypeScript knows:
numbers; // number[]
names; // string[]Generic Function with Arrays
function getLast<T>(items: T[]): T {
return items[items.length - 1];
}
const lastNumber = getLast([1, 2, 3]);
const lastUser = getLast(["Mihir", "Alex"]);The return type depends on the array item type.
Multiple Type Parameters
function pair<T, U>(first: T, second: U): [T, U] {
return [first, second];
}
const result = pair("age", 28);TypeScript infers:
result; // [string, number]Generic Function Expression
const identity = <T,>(value: T): T => {
return value;
};The comma after T is sometimes used in .tsx files so TypeScript does not confuse generics with JSX.
In normal .ts files, this also works:
const identity = <T>(value: T): T => value;Generic Callback Example
function mapItems<T, U>(items: T[], callback: (item: T) => U): U[] {
return items.map(callback);
}
const lengths = mapItems(["one", "three"], (word) => word.length);T is string.
U is number.
So lengths is number[].
Avoid Unnecessary Generics
This generic is not useful:
function greet<T>(name: string): string {
return `Hello, ${name}`;
}T is not used, so it adds confusion.
Only add generics when they connect types in a meaningful way.
Quick Recap
- Generic functions use type parameters like
<T>. - TypeScript usually infers generic types from arguments.
- Multiple type parameters are allowed.
- Generics are useful when input and output types are related.
- Avoid generic parameters that are not used.
Next up, we will learn Generic Interfaces →.