Close

TypeScript - Using Generics In Functions

[Last Updated: Oct 7, 2018]

This tutorial shows how to use generics in functions.

Examples

class Pair<F, S> {
    first: F;
    second: S;

    constructor(first: F, second: S) {
        this.first = first;
        this.second = second;
    }
}

//using generics in a function
function getFirstArray<F, S>(pairs: Pair<F, S>[]): F[] {
    let arr: F[] = [];
    for (let i = 0; i < pairs.length; i++) {
        let first: F = pairs[i].first;
        arr.push(first);
    }
    return arr;
}

let numArray: Pair<number, boolean>[] = [new Pair(1, true),
    new Pair(2, false), new Pair(3, true)];

console.log(getFirstArray(numArray));

Output

[ 1, 2, 3 ]

Following example shows how to search an array generically by providing a search function.

function findFirst<T>(items: T[], searchFunction: (t: T) => boolean): T {
    for (let i = 0; i < items.length; i++) {
        let item: T = items[i];
        if (searchFunction(item)) {
            return item;
        }
    }
    return null;
}

let items: number[] = [1, 4, 7, 9];
let n: number = findFirst<number>(items, (t: number) => t % 2 == 0);
console.log(n);

let items2: string[] = ["one", "two", "three"];
let s: string = findFirst<string>(items2, (s: string) => s.indexOf("wo") != -1);
console.log(s);

Output

4
two

Example Project

Dependencies and Technologies Used:

  • TypeScript 3.1.1
Using Generics In Functions Select All Download
  • typescript-generics-in-functions
    • interface-generics-in-function.ts

    See Also