Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to Develop Generic Classes
Generic classes in TypeScript allow you to create flexible, reusable classes that can work with multiple data types. They use type parameters enclosed in angle brackets (<>) to represent the type of data the class will handle, making your code more versatile and type-safe.
A generic class uses type parameters (commonly denoted as "T") as placeholders for actual types. When you instantiate the class, you specify the concrete type, and the class properties and methods adapt accordingly. This approach eliminates code duplication while maintaining type safety.
Syntax
The basic syntax for creating a generic class in TypeScript is:
class ClassName<TypeParameter> {
// class properties and methods
}
Where "ClassName" is the name of the class, and "TypeParameter" is the placeholder for the type of data the class will work with.
Example: Generic Queue Class
This example demonstrates a generic Queue class that can handle different data types. The class uses type parameter T to ensure type safety while maintaining flexibility:
class Queue<T> {
private data: T[] = []
// add an item to the end of the queue
enqueue(item: T): void {
this.data.push(item)
}
// remove an item from the front of the queue
dequeue(): T | undefined {
return this.data.shift()
}
// get the item at the front of the queue
peek(): T | undefined {
return this.data[0]
}
}
// Creating a queue for numbers
let numberQueue = new Queue<number>()
numberQueue.enqueue(1)
numberQueue.enqueue(2)
console.log(numberQueue.peek())
console.log(numberQueue.dequeue())
console.log(numberQueue.peek())
// Creating a queue for strings
let stringQueue = new Queue<string>()
stringQueue.enqueue('Hello')
stringQueue.enqueue('world')
console.log(stringQueue.peek())
console.log(stringQueue.dequeue())
console.log(stringQueue.peek())
When compiled to JavaScript, it produces:
var Queue = /** @class */ (function () {
function Queue() {
this.data = [];
}
Queue.prototype.enqueue = function (item) {
this.data.push(item);
};
Queue.prototype.dequeue = function () {
return this.data.shift();
};
Queue.prototype.peek = function () {
return this.data[0];
};
return Queue;
}());
var numberQueue = new Queue();
numberQueue.enqueue(1);
numberQueue.enqueue(2);
console.log(numberQueue.peek());
console.log(numberQueue.dequeue());
console.log(numberQueue.peek());
var stringQueue = new Queue();
stringQueue.enqueue('Hello');
stringQueue.enqueue('world');
console.log(stringQueue.peek());
console.log(stringQueue.dequeue());
console.log(stringQueue.peek());
1 1 2 Hello Hello world
Multiple Generic Types
Generic classes can accept multiple type parameters. Here's a KeyValuePair class with two generic types:
class KeyValuePair<T, U> {
private key: T
private value: U
constructor(key: T, value: U) {
this.key = key
this.value = value
}
getKey(): T {
return this.key
}
getValue(): U {
return this.value
}
}
// String key with number value
let numberPair = new KeyValuePair<string, number>('age', 25)
console.log(numberPair.getKey())
console.log(numberPair.getValue())
// String key with object value
let objectPair = new KeyValuePair<string, object>('person', {
name: 'Tutorialspoint',
age: 10
})
console.log(objectPair.getKey())
console.log(objectPair.getValue())
The compiled JavaScript output:
var KeyValuePair = /** @class */ (function () {
function KeyValuePair(key, value) {
this.key = key;
this.value = value;
}
KeyValuePair.prototype.getKey = function () {
return this.key;
};
KeyValuePair.prototype.getValue = function () {
return this.value;
};
return KeyValuePair;
}());
var numberPair = new KeyValuePair('age', 25);
console.log(numberPair.getKey());
console.log(numberPair.getValue());
var objectPair = new KeyValuePair('person', {
name: 'Tutorialspoint',
age: 10
});
console.log(objectPair.getKey());
console.log(objectPair.getValue());
age
25
person
{ name: 'Tutorialspoint', age: 10 }
Key Benefits
| Benefit | Description |
|---|---|
| Type Safety | Compile-time type checking prevents runtime errors |
| Code Reusability | One class works with multiple data types |
| Maintainability | Reduces code duplication and improves clarity |
Conclusion
Generic classes in TypeScript provide a powerful way to create flexible, type-safe code that works with multiple data types. They combine the benefits of strong typing with code reusability, making your applications more robust and maintainable.
