Generic Functions
In this page:
function name<T>(param: T): T {
return param;
}
name<type>(value);
Creating a Generic Function
Put a type parameter after the function name and use it in the parameter and return types; this is what actually connects the input type to the output type instead of writing the function once per concrete type.
Example: Creating a Generic Function
function identity<T>(value: T): T {
return value;
}
console.log(identity<number>(10));
Generic Functions with Arrays
Generic functions can accept arrays and return elements while preserving their element type, so calling the function on a string[] still gives back a string, not a value TypeScript has to widen to any.
Example: Generic Functions with Arrays
function firstElement<T>(arr: T[]): T {
return arr[0];
}
console.log(firstElement(["a", "b", "c"]));
Generic Arrow Functions
Arrow functions can also declare generic type parameters, and are useful for compact utility functions like a generic identity or comparator that need to stay short but still fully type-safe.
Example: Generic Arrow Functions
const identity = <T,>(value: T): T => value;
console.log(identity(99));
Generic Functions with Objects
Generic functions can preserve the exact type of objects passed to them, so a function that just forwards or wraps a value doesn't accidentally erase useful information about that value's shape.
Example: Generic Functions with Objects
function wrap<T>(value: T): { data: T } {
return { data: value };
}
console.log(wrap({ name: "Nia" }));
Explicit Type Arguments
You can explicitly provide a type argument (like identity<string>(x)) when you want to make the intended type clear, or when TypeScript's inference genuinely can't determine it from the arguments alone.
Example: Explicit Type Arguments
function identity<T>(value: T): T {
return value;
}
console.log(identity<string>("explicit"));
- Putting the type parameter in the wrong place, like
function<T> identity(value: T), when it goes after the function name:identity<T>. - Using a generic parameter but never using
Tin the parameters or return type, so it adds nothing. - In a
.tsxfile writingconst f = <T>(x: T) => x, which is parsed as JSX; use<T,>or a function declaration.
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: