To handle array operations with multiple generic parameters in TypeScript, you can use a combination of generic classes, functions, and interfaces. Here's an example:
typescript
// Generic interface
interface ArrayOperations<T, U> {
zip(arr1: T[], arr2: U[]): [T, U][];
filter(arr: (T | U)[], predicate: (item: T | U) => boolean): (T | U)[];
}
// Generic class implementing the ArrayOperations interface
class GenericArrayUtils<T, U> implements ArrayOperations<T, U> {
zip(arr1: T[], arr2: U[]): [T, U][] {
return arr1.map((item, index) => [item, arr2[index]]);
}
filter(arr: (T | U)[], predicate: (item: T | U) => boolean): (T | U)[] {
return arr.filter(predicate);
}
}
// Usage example
const utils = new GenericArrayUtils<number, string>();
const numbers = [1, 2, 3];
const strings = ["a", "b", "c"];
const zipped = utils.zip(numbers, strings);
console.log(zipped); // Output: [[1, "a"], [2, "b"], [3, "c"]]
const filtered = utils.filter([1, "a", 2, "b", 3, "c"], (item) => typeof item === "number");
console.log(filtered); // Output: [1, 2, 3]
In this example, we have:
1. Generic Interface: The `ArrayOperations` interface defines two methods, `zip` and `filter`, that take two generic type parameters `T` and `U`.
2. Generic Class: The `GenericArrayUtils` class implements the `ArrayOperations` interface, providing implementations for the `zip` and `filter` methods. The class also takes two generic type parameters `T` and `U`.
3. Usage Example: We create an instance of the `GenericArrayUtils` class, passing `number` and `string` as the generic type parameters. We then use the `zip` and `filter` methods to perform operations on arrays of `number` and `string` values.
The key points to note are:
- The generic interface `ArrayOperations` defines the contract for the array operations, allowing us to create reusable components.
- The generic class `GenericArrayUtils` implements the `ArrayOperations` interface, providing the actual implementation of the array operations.
- The generic type parameters `T` and `U` allow the class and its methods to work with different data types, ensuring type safety.
- In the usage example, we create an instance of `GenericArrayUtils` and use it to perform array operations on `number` and `string` arrays.
By using multiple generic parameters, you can create flexible and reusable array operations that can handle a variety of data types, ensuring type safety and maintainability in your TypeScript codebase.
Citations:[1] https://www.youtube.com/watch?v=g0MSer7WxVc
[2] https://www.geeksforgeeks.org/typescript-generic-classes/
[3] https://www.scaler.com/topics/typescript/generic-classes-in-typescript/
[4] https://stackoverflow.com/questions/74151482/typescript-array-of-different-generics
[5] https://blog.logrocket.com/using-typescript-generics-create-reusable-components/