Close

TypeScript - Generic classes

[Updated: Oct 6, 2018, Created: Oct 6, 2018]

In programming world, Generics provide a way to express types as 'parameters' where actual types for those parameters are specified at the time of invocation/instantiation.

TypeScript allows the use of generics in many places. This tutorial shows how to use generic type parameters in classes.

Example

class List<T> {
    private data: T[];

    constructor(...elements: T[]) {
        this.data = elements;
    }

    add(t: T) {
        this.data.push(t);
    }

    remove(t: T) {
        let index = this.data.indexOf(t);
        if (index > -1) {
            this.data.splice(index, 1);
        }
    }

    asArray(): T[] {
        return this.data;
    }
}

let numbers = new List<number>(1, 3, 6, 7);
numbers.add(11);
numbers.remove(3);
let numArray = numbers.asArray();
console.log(numArray);

let fruits = new List<string>("apple", "banana", "orange");
fruits.add("mango");
fruits.remove("apple");
let fruitArray = fruits.asArray();
console.log(fruitArray);

Output

[ 1, 6, 7, 11 ]
[ 'banana', 'orange', 'mango' ]

In above example T is a generic type parameter. It represents the type of the element in a List. Once we have initiated a List with a particular type (say new List<number>(....)) then all methods like add(T) and remove(T) should supply the same type i.e. number, otherwise there will be a compile time error.

Using multiple type parameters

class Pair<F, S> {
    private _first: F;
    private _second: S;

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

    get first(): F {
        return this._first;
    }

    get second(): S {
        return this._second;
    }
}

let pair = new Pair<number, boolean>(10, true);
console.log(pair.first);
console.log(pair.second);
console.log(pair);

let pair2 = new Pair<string, number>("1K", 1000);
console.log(pair2.first);
console.log(pair2.second);
console.log(pair2);

Output

10
true
Pair { _first: 10, _second: true }
1K
1000
Pair { _first: '1K', _second: 1000 }

Example Project

Dependencies and Technologies Used:

  • TypeScript 3.1.1
Generic Type Parameters in Classes Select All Download
  • typescript-generic-classes
    • generic-class-example.ts

    See Also