Sub topic 2
Generic Functions and Type Parameters
This chapter assumes you can annotate function parameters and return types, read union types, and write object types with interfaces or type aliases. It covers the basic mechanics of a generic function: declaring type parameters, using them in a signature, passing type arguments explicitly, and the limits on what a function body can do with a value of type T. Later chapters cover inference rules, constraints, and generic types and classes in detail.
The problem a type parameter solves
Suppose you want a function that returns whatever it is given. With any, it compiles, but the type information is lost:
function identityAny(value: any): any {
return value;
}
const result = identityAny("hello"); // type: any
result.toFixed(2); // compiles, then throws at runtime: strings have no toFixedThe compiler cannot connect the type of the argument to the type of the result. A union such as string | number doesn't fix this, because the result would still be the whole union. You would need an overload for every type you want to support.
A type parameter fixes this. It is a placeholder for a type that the caller chooses. The function is written once, and each call fills in the placeholder.
Declaring a type parameter
Type parameters go in angle brackets after the function name, before the parameter list:
function identity<T>(value: T): T {
return value;
}
const a = identity<string>("hello"); // a: string
const count: number = 42;
const b = identity(count); // b: number, T inferred from the argumentRead the signature as "for any type T, take a T and return a T." The name T is a convention, not a keyword. T stands for "type", and you can use any valid identifier. Short names are the norm when a parameter has no special meaning. Descriptive names such as TItem or Input are better when a signature has several parameters or complex relationships.
Here is how the call is processed:
The type parameter exists only at compile time. After compilation, the emitted JavaScript contains no trace of T.
How generics compare to the alternatives
| Approach | Accepts any type | Keeps the caller's type in the result | Safe to use the result |
|---|---|---|---|
| `any` | Yes | No, result is `any` | No, checks are turned off |
| `unknown` | Yes | No, result is `unknown` | Only after narrowing |
| Overloads | Only listed types | Yes, for each listed type | Yes, but each type needs a signature |
| Generic `<T>` | Yes | Yes | Yes, within what `T` is known to allow |
Several type parameters
A signature can declare as many type parameters as it needs. Separate them with commas:
function pair<A, B>(first: A, second: B): [A, B] {
return [first, second];
}
const p = pair("age", 30); // [string, number]Each parameter is bound independently. If two parameters should share one type, use the same type parameter for both. If they may differ, use two.
The most common reason for a second parameter is a transformation, where the output type differs from the input type:
function mapArray<T, U>(items: T[], transform: (item: T) => U): U[] {
const result: U[] = [];
for (const item of items) {
result.push(transform(item));
}
return result;
}
const lengths = mapArray(["a", "bb", "ccc"], (s) => s.length); // number[]Here T comes from the array, and U comes from what the callback returns. The compiler infers T as string from the first argument. That lets it type s inside the callback as string, and it then infers U as number from the callback's return value. Information flows from earlier arguments into later ones, which is why the callback parameter needs no annotation.
Other forms of generic functions
Type parameters are not limited to function declarations. Arrow functions, function expressions, and methods can all declare them:
const wrap = <T,>(value: T): { value: T } => ({ value });
const boxed = wrap("text"); // { value: string }The trailing comma in <T,> is for .tsx files. In a .tsx file, <T>(...) could be read as a JSX tag, and the comma makes it unambiguous. In a plain .ts file you can write <T>.
You can also describe a generic function as a type. The type parameter belongs to the call, so each call picks its own T:
type Transformer = <T>(input: T) => T;
const same: Transformer = (x) => x;
const s = same("a"); // string
const n = same(1); // numberCompare this with type Fn<T> = (input: T) => T. There, T is fixed when you write Fn<string>, and the resulting function handles only strings. In Transformer, T is chosen at every call. Where the angle brackets sit decides which one you have.
Supplying type arguments explicitly
You can pass type arguments yourself with the same angle-bracket syntax:
function identity<T>(value: T): T {
return value;
}
identity<string>("hello"); // OK
// identity<string>(42); // Error: Argument of type 'number' is not assignable to parameter of type 'string'An explicit argument overrides inference, and the arguments are then checked against it. There are two rules to remember:
- You must supply all type arguments or none.
pair<string>("a", 1)is an error becausepairexpects two type arguments. (Defaults, covered in a later chapter, relax this.) - Type arguments are matched by position, in the order the parameters were declared.
Explicit arguments are most useful when there is nothing to infer from. An example is an empty array, where the compiler has no element type to work with:
function createList<T>(): T[] {
return [];
}
const names = createList<string>(); // string[]
const guess = createList(); // unknown[]When no inference candidate exists, T falls back to unknown. That is why the second call produces unknown[].
What a function body may do with T
Inside the body, the compiler knows nothing about T. The function must work for every possible type, so it may only do things that are valid for every type. Assigning, returning, and passing the value to something that accepts anything are all allowed. Anything more specific is rejected:
function lengthOf<T>(value: T): number {
// return value.length; // Error: Property 'length' does not exist on type 'T'
return 0;
}The error is correct. A caller could pass a number, which has no length. To use .length you must tell the compiler that T is restricted to types that have it. That restriction is a constraint, and it is the subject of a later chapter.
Type parameters are also erased at runtime, so they cannot be used where a value is needed:
function make<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 from a type parameter");
}If you need to create instances, pass in a constructor or a factory function as an ordinary argument. The type parameter can then describe what that function produces.
Common mistakes with type parameters
- Using a type parameter once. If
Tappears in only one place in a signature, it links nothing to anything else. A plainunknownor a concrete type usually says the same thing more simply. - Assuming the return type is checked against the body. A body can satisfy the compiler through a cast such as
return value as T. The cast hides a mismatch instead of fixing it. If you need a cast to make a generic body compile, the signature probably promises more than the body delivers. - Expecting partial explicit arguments. Writing one of two type arguments fails. Supply both, or let inference handle both.
- Confusing the two placements of
<T>.<T>(x: T) => Tis a function that is generic per call.Fn<T>is a type that must be givenTup front. - Reusing one name for unrelated roles. Declaring
<T, U>and then usingTfor both the input and the output merges two types you meant to keep separate. Use a second parameter whenever two values may differ.
Practice
Exercise
Write a generic function last that takes an array of any element type and returns its final element, or undefined if the array is empty. What does last([true, false]) return type look like, and why?
Show answer
function last<T>(items: T[]): T | undefined { return items[items.length - 1]; }. The call last([true, false]) has return type boolean | undefined. The compiler infers T as boolean from the array argument, then substitutes it into the declared return type T | undefined.
Exercise
The signature function combine<A, B>(x: A, y: B): A has a problem when it is written as function combine<A, B>(x: A, y: B): A { return y; }. Why does the body fail to compile, and what are two valid ways to fix it?
Show answer
The body returns y, which has type B, but the signature promises A. A and B are independent type parameters, so B is not assignable to A. One fix is to return x instead. The other is to change the return type to B so it matches the body.