This tutorial aims to guide you through the process of building generic classes and components in TypeScript.
You will learn how to create flexible, reusable classes and components that can handle a variety of data types.
In TypeScript, Generics promote code reusability while keeping type safety. They are like the placeholders for any data type that gets determined at the time of function invocation or class instance creation.
A generic class has a similar shape to a generic interface. A generic class has a generic type parameter list in angle brackets (<>) following the name of the class.
class GenericClass<T> {
value: T;
add: (x: T, y: T) => T;
}
In the above code, T
is a type variable—a kind of variable that works on types rather than values.
number
typeclass GenericNumber<T> {
zeroValue: T;
add: (x: T, y: T) => T;
}
let myGenericNumber = new GenericNumber<number>();
myGenericNumber.zeroValue = 0;
myGenericNumber.add = function(x, y) { return x + y; };
console.log(myGenericNumber.add(3, 4));
In this example, we create an instance of GenericNumber
for number
type. The add
function is provided which takes two arguments of type T
and returns a value of type T
.
Expected output: 7
string
typelet stringNumeric = new GenericNumber<string>();
stringNumeric.zeroValue = "";
stringNumeric.add = function(x, y) { return x + y; };
console.log(stringNumeric.add(stringNumeric.zeroValue, "test"));
Here, we're creating a class with string
type. The add
function concatenates two strings.
Expected output: test
Continue exploring more advanced topics in TypeScript like Generic Constraints, Default values in Generics and using multiple type variables in Generics.
Create a generic class KeyValuePair
that contains key-value pairs of any type.
Create a generic function that accepts an array of any type and prints each element.
// Solution to Exercise 1
class KeyValuePair<T, U> {
private key: T;
private val: U;
setKeyValue(key: T, val: U) {
this.key = key;
this.val = val;
}
display() {
console.log(`key = ${this.key}, val = ${this.val}`);
}
}
// Solution to Exercise 2
function printArray<T>(items : T[] ) : void {
for(let i = 0; i<items.length; i++) {
console.log(items[i]);
}
}
Try to implement a generic stack or queue data structure, and work with more complex data types.