Introduction to Generics in TypeScript
Generics is a powerful feature in TypeScript that allows us to create reusable code components. It enables us to write code that can work with a variety of data types instead of just one. Generics provide a way to write type-safe code without knowing the specific type at compile time.
Generic Functions in TypeScript
We can create generic functions in TypeScript using the <T>
syntax. Here’s an example:
function reverse<T>(arr: T[]): T[] {
return arr.reverse();
}
const numbers = [1, 2, 3];
const reversedNumbers = reverse(numbers); // [3, 2, 1]
const strings = ['hello', 'world'];
const reversedStrings = reverse(strings); // ['dlrow', 'olleh']
In the above code, we have created a generic function called reverse
that takes an array of type T
and returns an array of the same type. We can call this function with arrays of any data type.
Generic Interfaces in TypeScript
We can also create generic interfaces in TypeScript. Here’s an example:
interface KeyValuePair<K, V> {
key: K;
value: V;
}
const kv1: KeyValuePair<number, string> = { key: 1, value: 'hello' };
const kv2: KeyValuePair<string, boolean> = { key: 'world', value: true };
In the above code, we have created a generic interface called KeyValuePair
that takes two type parameters K
and V
. We can use this interface to create objects with any combination of key and value types.
Generic Classes in TypeScript
We can also create generic classes in TypeScript. Here’s an example:
class Stack<T> {
private items: T[] = [];
push(item: T) {
this.items.push(item);
}
pop(): T | undefined {
return this.items.pop();
}
}
const stack = new Stack<number>();
stack.push(1);
stack.push(2);
stack.push(3);
console.log(stack.pop()); // 3
console.log(stack.pop()); // 2
console.log(stack.pop()); // 1
In the above code, we have created a generic class called Stack
that takes a type parameter T
. This class represents a stack data structure and allows us to push and pop items of any data type.
Conclusion
Generics are a powerful feature in TypeScript that allows us to write reusable code components. We can create generic functions, interfaces, and classes that can work with a variety of data types. By using generics, we can write type-safe code without knowing the specific type at compile time.