Sub topic 1
Why Generics Exist
Generics let one function, type, or class work with many types without losing track of which type is in use at each call. This chapter explains the problem they solve. It does so by trying the alternatives first: duplication, any, unknown, and overloads. Each alternative fails in a specific way, and seeing the failures makes the syntax in later chapters easier to follow.
Prerequisites
This chapter assumes you already know:
- Basic TypeScript types:
string,number, arrays, and object types. - How to write interfaces and type aliases.
- How to annotate function parameters and return types.
- Union types such as
string | number. - Basic class syntax.
You do not need any prior knowledge of generics. You should be able to run TypeScript code with tsc or a playground and read compiler error messages.
The problem: reuse versus type information
Consider the simplest reusable function there is: one that returns whatever it receives. For a number you could write this:
function identityNumber(value: number): number {
return value;
}That works, but it only accepts numbers. Supporting strings means writing identityString, and supporting booleans means writing identityBoolean. The bodies are identical. Only the types differ.
The goal is to write the logic once and still have the compiler know that a string went in and a string came out. That goal has two parts. Reuse means one implementation serves many types. Type information means the result keeps the exact type of the input. Every approach below gets one part, and generics get both.
Attempt 1: any
The quickest way to accept every type is any:
function identityAny(value: any): any {
return value;
}
const result = identityAny("hello");
result.toFixed(2); // compiles, but throws at runtime: result is a stringThe function is reusable, but result has type any. The compiler remembers nothing about what went in. It lets you call toFixed on a string, so the mistake only appears when the program runs. Worse, any spreads. Anything computed from result is also any, so one any can switch off checking across a whole call chain.
Attempt 2: unknown
unknown is the safer top type. You can assign anything to it, but you cannot use a value of that type until you narrow it:
function identityUnknown(value: unknown): unknown {
return value;
}
const r = identityUnknown("hello");
// r.toUpperCase(); // Error: 'r' is of type 'unknown'
if (typeof r === "string") {
console.log(r.toUpperCase()); // OK after narrowing
}This is honest, because the compiler admits it does not know the type. But the information was still lost. The caller passed a string and must now prove to the compiler that it is a string. For a function that is supposed to return its argument unchanged, that is wasted work.
Attempt 3: overloads
Overloads declare several signatures for one implementation, so each input type maps to the matching output type:
function wrap(value: string): { value: string };
function wrap(value: number): { value: number };
function wrap(value: string | number): { value: string | number } {
return { value };
}
const w1 = wrap("hi"); // { value: string }
const w2 = wrap(5); // { value: number }
// wrap(true); // Error: no overload accepts booleanOverloads do preserve type information, but you must list every supported type by hand. Adding boolean means adding another signature. Arrays, objects, and your own interfaces would each need one too. The set of types is closed, so a caller with a type you did not anticipate is stuck. Overloads are the right tool when different input types really do need different return types that no single rule describes. They are the wrong tool when the rule is simply "same type out as in".
The generic solution
A generic function declares a type parameter, a placeholder for a type that is filled in at each call:
function identity<T>(value: T): T {
return value;
}
const a = identity<string>("hello"); // string
const b = identity(42); // number, inferred<T> introduces the type parameter. Writing value: T and : T ties the two positions together: whatever type T becomes, the argument and the return value have that same type. The name T is a convention. Any identifier works, and longer names like TItem are common in larger signatures.
The parameter is filled in per call, not once for the whole function. The same identity produces string for one call and number for the next, and the compiler checks each call separately.
// identity<string>(42); // Error: Argument of type 'number' is not assignable to parameter of type 'string'The first call supplies T explicitly. The second leaves it out, and TypeScript works it out from the argument. The next chapters cover that inference in detail.
The working model
Think of a generic function as a function that runs at compile time on types. At each call site, the compiler picks a concrete type for T, replaces T in the signature, and checks the call against the result.
Two consequences follow from this model.
- The compiler erases types. After compilation,
identityis plain JavaScript with no trace ofT. Generics cost nothing at runtime and give you no runtime information either. - Inside the body,
Tis opaque. The function must work for every possibleT, so the compiler only lets you do things that are valid for every type. You cannot call.lengthon aT, becauseTmight be a number. Chapter 6 shows how to relax this with constraints.
Comparing the approaches
| Approach | One implementation | Keeps input type in output | Handles unforeseen types | Main risk |
|---|---|---|---|---|
| Duplicate functions | No | Yes | No | Copies drift apart |
| `any` | Yes | No | Yes | Errors move to runtime |
| `unknown` | Yes | No | Yes | Caller must re-narrow |
| Overloads | Yes | Yes | No | Every type listed by hand |
| Generics | Yes | Yes | Yes | Misuse adds noise |
Generics are the only row with a "Yes" in every capability column. That is the reason they exist.
Common errors when starting out
Returning something that is not T
A generic function must return a value of type T, not a value that merely looks compatible:
function broken<T>(value: T): T {
// return 0; // Error: Type 'number' is not assignable to type 'T'.
return value;
}The caller might choose T = string, and then returning 0 would break the promise. The compiler rejects any return that cannot be proven to be a T.
Treating T as a runtime value
Because types are erased, T does not exist when the program runs. You cannot compare against it, construct it, or branch on it:
function create<T>(): T {
// return new T(); // Error: 'T' only refers to a type, but is being used as a value here.
throw new Error("cannot construct a type that does not exist at runtime");
}If you need to create instances, pass in a constructor or factory function as an ordinary argument. The type parameter then describes what that function returns.
Reaching for any inside a generic
A common shortcut is to write value as any to silence an error inside a generic function. That removes the safety you introduced the type parameter to get, and the error usually points to a missing constraint or a wrong design. Fix the signature rather than casting away the check.
Adding type parameters that do nothing
A type parameter is worth having when it links two or more positions, such as an argument and the return type. A parameter used once links nothing and only adds noise. Chapter 14 covers this pitfall and the rule of thumb for spotting it.
What comes next
The rest of this tutorial builds on the idea from this chapter:
- Generic functions and type parameters, in more detail.
- How TypeScript infers type arguments, and when to supply them yourself.
- Generic interfaces, type aliases, and classes.
- Constraints with
extends, pluskeyofand indexed access types. - Default type parameters, mapped types, built-in utility types, and conditional types.
- Common pitfalls and the basics of variance.
Each of these is a way to describe a relationship between types, which is what a generic does in its simplest form.
Exercise
A teammate writes function last(items: any[]): any { return items[items.length - 1]; }. Rewrite it as a generic function so that last([1, 2, 3]) has type number | undefined and last(["a"]) has type string | undefined. Then explain why the any version fails to catch last([1, 2, 3]).toUpperCase().
Show answer
Use a type parameter for the element type: function last<T>(items: T[]): T | undefined { return items[items.length - 1]; }. For [1, 2, 3], TypeScript infers T as number, so the result is number | undefined. For ["a"] it infers string. The any version returns any, so the compiler has no element type to check against and allows .toUpperCase() on a number. The call crashes at runtime. In the generic version, the same call is a compile-time error, because number | undefined has no toUpperCase method.
Exercise
Why does function make<T>(): T { return new T(); } fail to compile, and what is the usual fix?
Show answer
Type parameters exist only at compile time and are erased from the emitted JavaScript, so T cannot be used as a value. new T() has nothing to construct at runtime. The usual fix is to pass a constructor or factory function as an argument, for example function make<T>(create: () => T): T { return create(); }. The type parameter then describes the factory's return type.