Sub topic 9
Generic Functions
This chapter assumes you know JavaScript functions, callbacks, arrays, union types, and basic TypeScript annotations. It also assumes you can run TypeScript with tsc or an editor.
A generic function works with several types while preserving the relationship between its inputs and outputs. A type parameter is a placeholder for a type. By convention, type parameters use names such as T.
function identity<T>(value: T): T {
return value;
}
const count = identity(42); // number
const message = identity("hello"); // stringWhen TypeScript checks identity(42), it infers T as number. When it checks identity("hello"), it infers T as string. The function has one implementation, but each call keeps its own type.
Why use a generic function?
Without generics, you might use any:
function firstItem(items: any[]): any {
return items[0];
}This accepts every array, but the result loses useful type information. A generic version keeps the element type:
function firstItem<T>(items: T[]): T | undefined {
return items[0];
}
const firstNumber = firstItem([10, 20, 30]); // number | undefined
const firstWord = firstItem(["red", "blue"]); // string | undefinedThe T[] parameter says that the array contains values of one type. The T | undefined return type reflects that an empty array has no first item.
Generic callbacks
Generics can describe relationships between a collection and a callback. A reusable callback type is often clearer as a type alias.
type Predicate<T> = (value: T) => boolean;
function filterItems<T>(items: T[], keep: Predicate<T>): T[] {
return items.filter(keep);
}
const evens = filterItems([1, 2, 3, 4], n => n % 2 === 0);
// number[]
const longWords = filterItems(["cat", "elephant", "dog"], word => word.length > 3);
// string[]TypeScript infers T from the array. It then uses that type to contextually type the callback parameter. In this example, n is a number, and word is a string.
Supplying type arguments explicitly
Inference usually gives the best result, but you can provide a type argument between angle brackets:
function pair<T>(value: T): [T, T] {
return [value, value];
}
const dates = pair<Date>(new Date()); // [Date, Date]Explicit type arguments can document intent or resolve an ambiguous call. They cannot make an invalid value safe:
// pair<number>("not a number"); // errorMultiple type parameters
A function can preserve relationships between several values with multiple type parameters.
function mapObject<K extends PropertyKey, V, R>(
entries: Array<[K, V]>,
transform: (value: V) => R
): Map<K, R> {
const result = new Map<K, R>();
for (const [key, value] of entries) {
result.set(key, transform(value));
}
return result;
}
const lengths = mapObject(
[["a", "cat"], ["b", "elephant"]],
word => word.length
);
// Map<string, number>Here, K is the key type, V is the original value type, and R is the transformed value type. The constraint K extends PropertyKey ensures that K can be used as a Map key.
Exercise
Write a generic function named lastItem that accepts an array of T and returns T | undefined.
Show answer
function lastItem<T>(items: T[]): T | undefined { return items[items.length - 1]; }