Sub topic 1
TypeScript Generics: Writing Reusable, Type-Safe Code
Prerequisites
This chapter assumes you know basic TypeScript types, interfaces, type aliases, functions, unions, arrays, and classes.
Why Generics Exist
Generics let one function or type work with many types while preserving the specific type used at each call site. A generic type parameter is a placeholder for a type.
Without generics, you might use any:
function firstValue(items: any[]): any {
return items[0];
}This accepts everything, but the result loses useful type information. A generic function keeps the connection between its input and output:
function firstElement<T>(items: T[]): T | undefined {
return items[0];
}
const numberValue = firstElement([1, 2, 3]); // number | undefined
const textValue = firstElement(["a", "b"]); // string | undefinedT changes for each call, so the function remains reusable and type-safe.
Generic Functions and Type Parameters
A type parameter appears in angle brackets after the function name. It can connect an argument to the return value:
function identity<T>(value: T): T {
return value;
}
const message = identity<string>("hello"); // string
const count = identity(42); // numberThe explicit <string> supplies a type argument. The second call lets TypeScript determine T.
How TypeScript Infers Type Arguments
Type argument inference means TypeScript chooses a type argument from the values passed to a function. Inference usually makes calls shorter:
function pair<T>(first: T, second: T): T[] {
return [first, second];
}
const values = pair(1, 2); // number[]Supply a type argument when inference is unclear, when you want a broader type, or when you want the call to document its intended type.
Generic Interfaces and Type Aliases
Interfaces and type aliases can also use parameters:
interface Box<T> {
value: T;
}
type Pair<A, B> = [A, B];
const box: Box<number> = { value: 10 };
const entry: Pair<string, boolean> = ["active", true];The caller chooses the concrete types. The same definition then describes many related shapes without copying it.
Exercise
What type does firstElement(["red", "blue"]) return?
Show answer
string | undefined, because T is inferred as string and the array might be empty.