Sub topic 1
Why Generics Exist
Generics let one piece of TypeScript code work with different types while preserving the specific type used at each call. They solve a common problem: reusable code should not have to give up useful type information.
Prerequisites
This chapter assumes you know basic TypeScript types such as string, number, arrays, and object types. You should also understand interfaces, type aliases, function annotations, union types, and basic class syntax.
The Problem with `any`
Suppose a function returns the value it receives:
function identity(value: any): any {
return value;
}
const result = identity("hello");
result.toUpperCase(); // TypeScript allows thisThe function accepts every value, but any removes the connection between the input and output. TypeScript cannot tell that result is a string because the function promises only any. This also allows mistakes:
const numberResult = identity(42);
numberResult.toUpperCase(); // No error during type checkingThe code may fail when it runs. any is sometimes useful at an unsafe boundary, but it should not be the default way to make an API reusable.
Generics Preserve the Relationship
A generic type parameter is a placeholder for a type. The caller supplies a type, either explicitly or through inference. The same placeholder can then connect multiple parts of a type signature.
function identity<T>(value: T): T {
return value;
}
const text = identity("hello"); // string
const count = identity(42); // numberHere, T means “the type provided for this call.” When the argument is a string, the return type is a string. When the argument is a number, the return type is a number.
The function has one implementation, but each call receives an appropriate type. This is the main benefit of generics: reuse without losing type information.
Generics Compared with Overloads
Function overloads describe several permitted call signatures. They work well when different inputs need different behavior or different output shapes.
Generics are usually clearer when the output type directly follows the input type. Without generics, overloads can repeat that relationship:
function first(items: string[]): string | undefined;
function first(items: number[]): number | undefined;
function first(items: string[] | number[]): string | number | undefined {
return items[0];
}
const word = first(["red", "blue"]); // string | undefinedThis handles only the listed element types. A generic version works for any element type:
function firstElement<T>(items: T[]): T | undefined {
return items[0];
}
const word = firstElement(["red", "blue"]); // string | undefined
const value = firstElement([10, 20]); // number | undefinedUse generics when the same type relationship applies broadly. Use overloads when the API has genuinely different cases that need separate signatures.
The Working Model
When reading a generic function, identify three things:
- The type parameter, such as
T. - Where the parameter appears in the inputs.
- Where the parameter appears in the result.
If T appears only once, it may not express a useful relationship:
function logValue<T>(value: T): void {
console.log(value);
}Since the type does not affect another part of the signature, unknown is often simpler:
function logValueSimple(value: unknown): void {
console.log(value);
}A generic is valuable when it tells TypeScript that multiple parts of an API share a type.
Exercise
Why is identity<T>(value: T): T safer than identity(value: any): any?
Show answer
The generic version links the argument and return types, so a string input produces a string result and a number input produces a number result. The any version preserves neither relationship.