Sub topic 2
Generic Functions and Type Parameters
This chapter assumes you know basic TypeScript types, interfaces, type aliases, function annotations, union types, and basic class syntax. Generics build on those features by allowing one function or type to work with different data types without discarding type information.
Why Generic Functions Exist
A generic function uses a type parameter, which is a placeholder for a type. The caller supplies a concrete type, either explicitly or through inference.
Consider an identity function. It returns the value it receives:
function identity<T>(value: T): T {
return value;
}
const message = identity<string>("hello");
const count = identity<number>(42);Here, T is the type parameter. The same T appears in the parameter type and the return type. This relationship tells TypeScript that the returned value has the same type as the argument.
identity<string>("hello") returns a string, while identity<number>(42) returns a number. The function does not need separate implementations for each type.
Without a generic, you might use any:
function identityUnsafe(value: any): any {
return value;
}This accepts and returns anything, but it provides no useful connection between the input and output. A caller could assume the result has the wrong type. Generics preserve the relationship while remaining reusable.
Type Parameters in Function Signatures
A type parameter is written between the function name and its parameter list:
function firstElement<T>(items: T[]): T | undefined {
return items[0];
}
const firstNumber = firstElement([10, 20, 30]);
const firstWord = firstElement(["red", "blue"]);TypeScript infers T as number for the first call and string for the second. Because an array can be empty, the return type includes undefined.
The parameter does not have to be an array. Any repeated use of the same type parameter can express a relationship:
function pairWithLabel<T>(value: T, label: string): [T, string] {
return [value, label];
}
const result = pairWithLabel(99, "score");
// result has type [number, string]The type parameter describes the value whose type varies. The label always remains a string.
Explicit Type Arguments and Inference
TypeScript usually infers type arguments from function arguments:
const numbers = firstElement([1, 2, 3]); // number | undefinedYou can provide a type argument explicitly when inference is unclear or when you want to check a specific choice:
const value = identity<string>("hello");An explicit type argument must satisfy the function's signature. This call is rejected because the argument is not a string:
// identity<string>(123); // ErrorInference is convenient, but it follows the values and expected types available at the call site. Do not assume that a generic function will always infer the type you intended.
A Practical Working Model
When reading a generic function, identify three things:
- The type parameter, such as
T. - Every place where that parameter appears.
- The concrete type TypeScript assigns at each call.
The main benefit is type preservation. The function implementation is written once, but each call keeps its own precise type.
Common Errors
- Replacing a meaningful generic relationship with
any. - Adding a type parameter that appears only once.
- Supplying an explicit type argument that conflicts with the value.
- Forgetting
undefinedwhen a generic function can return no value. - Assuming two arguments have the same type when the signature does not express that relationship.
Exercise
What is the inferred return type of firstElement(["a", "b"]), and why?
Show answer
The type is string | undefined. TypeScript infers T as string, and the array may be empty.