In TypeScript, you can define generic functions, interfaces, and classes like in other programming languages. A generic function has type parameters listed in angle brackets:
function reverseAndMerge<T>(arr1: T[], arr2: T[]): T[] {
return arr1.reverse().concat(arr2.reverse());
}
let arr1: number[] = [1, 2, 3];
let arr2: number[] = [4, 5, 6];
let arr = reverseAndMerge(arr1, arr2);
Such generic functions can be defined with generic interfaces as well. The function signature for reverseAndMerge is compatible with the following generic interface:
interface GenericArrayFn<T> {
(arr1: T[], arr2: T[]): T[];
}
let arr: GenericArrayFn<number> = reverseAndMerge;
Note that the generic type parameter list in angle brackets follows the name of the function and interface. This is also true for classes:
class GenericValue<T> {
constructor(private value: T) { }
increment: (x: T) => T;
decrement: (x: T) => T;
}
let genericValue = new GenericValue<number>(5);
genericValue.increment = function (x) {return ++x;};
genericValue.decrement = function (x) {return --x;};