TypeScript · Lesson 23 of 42
Generic functions: one function, many types
Learn generic functions with type parameters like <T>, how TypeScript infers them from arguments, and why generics beat any for reusable code.
UNDERSTAND IT. THEN TRY IT.
What you can do after this lesson
You will write functions that work on many types while staying fully type-checked. Generics are the feature that makes Array<T> and Promise<T> possible, and understanding them opens the door to the whole second half of the course.
The problem generics solve
Suppose you want a function that returns the first item of an array. You could write it for numbers, then again for strings, then for users. Or you could use any, but that loses information:
function firstAny(items: any[]): any {
return items[0];
}
const value = firstAny(["a", "b"]);
console.log(value);aThe result is any, so the compiler no longer knows it is a string, and any misuse compiles. You want the function to say "whatever type the array holds, I return that type". That is what a type parameter does.
A type parameter
Put a name in angle brackets after the function name. By convention it is a single capital letter, often T:
function first<T>(items: T[]): T | undefined {
return items[0];
}
const a = first(["x", "y"]);
const b = first([10, 20]);
console.log(a, b);
console.log(a?.toUpperCase(), b?.toFixed(1));x 10
X 10.0Read first<T>(items: T[]): T | undefined as: "for any type T, take an array of T and return a T or undefined". When you call first(["x", "y"]), TypeScript sees a string[], concludes T is string, and gives a the type string | undefined. For the numbers, T is number. The same function body serves both, and each result keeps its exact type, so toUpperCase works on a and toFixed on b.
Inference, and writing the type yourself
You almost never write the type parameter, because TypeScript infers it. You can write it explicitly with angle brackets at the call. That is useful when there is nothing to infer from, for example an empty array:
function first<T>(items: T[]): T | undefined {
return items[0];
}
const none = first<string>([]);
console.log(none);undefinedIf the explicit type contradicts the argument, you get the usual error:
function first<T>(items: T[]): T | undefined {
return items[0];
}
first<string>([1, 2, 3]);example.ts(5,16): error TS2322: Type 'number' is not assignable to type 'string'.
example.ts(5,19): error TS2322: Type 'number' is not assignable to type 'string'.
example.ts(5,22): error TS2322: Type 'number' is not assignable to type 'string'.Several type parameters
A function can have more than one, separated by commas. Each stands for an independent type:
function pair<A, B>(a: A, b: B): [A, B] {
return [a, b];
}
const p = pair("age", 30);
console.log(p);
console.log(p[0].toUpperCase(), p[1].toFixed(2));[ 'age', 30 ]
AGE 30.00The result is a tuple [string, number], because A was inferred from the first argument and B from the second.
Generics with callbacks
Generics shine when a function takes a callback, because the type flows through. Here is a simplified version of map:
function mapItems<T, U>(items: T[], fn: (item: T) => U): U[] {
const result: U[] = [];
for (const item of items) {
result.push(fn(item));
}
return result;
}
const lengths = mapItems(["apple", "fig"], word => word.length);
console.log(lengths);[ 5, 3 ]From the first argument T becomes string, so the callback parameter word is a string. From the callback's return value, U becomes number, so the result is a number[]. No annotations anywhere in the call. This chain of inference is what makes TypeScript pleasant in practice.
Arrow functions
Generic arrow functions put the type parameter before the parentheses:
const last = <T>(items: T[]): T | undefined => items[items.length - 1];
console.log(last([1, 2, 3]));3In a .tsx file (React), <T> looks like a JSX tag, so write <T,> there. In ordinary .ts files, no comma is needed.
When not to use generics
Generics add a small cost in readability, so use them when they do real work. A good test: the type parameter should appear at least twice in the signature, linking two places, such as the input and the output. If it appears only once, as in function log<T>(value: T): void, the parameter relates nothing and you can use a plain type, or unknown:
function log(value: unknown): void {
console.log("value:", value);
}
log("hello");value: helloCommon mistakes
Using any when T would keep the type. If the output depends on the input, a type parameter preserves the link.
Adding type parameters that do nothing. A parameter used once is noise.
Naming type parameters confusingly. Single letters such as T, U, K are conventional for simple cases. Use a descriptive name like TItem when there are several and their roles matter.
Calling a generic function without enough information. With nothing to infer from, TypeScript may fall back to unknown. Pass the type explicitly.
Expecting generics to exist at run time. They are erased, like all types. You cannot create a new T().
Exercise
Write function last<T>(items: T[]): T | undefined, function swap<A, B>(pair: [A, B]): [B, A] and function wrapInArray<T>(value: T): T[]. Check their inferred types by assigning results to annotated variables. Then write function filterBy<T>(items: T[], test: (item: T) => boolean): T[] and use it with numbers and with strings.
KNOWLEDGE CHECK
A quick check. You’ve got this.
Try each question. Every answer comes with an explanation.
Ready for the next small win?
Mark the lesson complete when you are ready.