Generic Class Example
This is an example of a generic class that stores data of any type.
class DataStorage<T> {
private data: T
constructor(data: T) {
this.data = data;
}
getData(): T {
return this.data;
}
}
Generic Function Example
This is an example of a generic function that reverses an array of any type.
function reverse<T>(itemArray: T[]): T[] {
return itemArray.reverse();
}
Generic Class Example
This is an example of a generic class that stores data of any type.
class DataStorage<T> {
private data: T
constructor(data: T) {
this.data = data;
}
getData(): T {
return this.data;
}
}
Generic Constraints
Generic constraints allow you to specify that a generic type must have certain properties
interface hasAge {
age: number
}
function getTotalAge<T extends hasAge>(people: T[]): number {
return people.reduce((total, person) => total + person.age, 0);
}
Generic Utility Function Example
This is an example of a generic utility function that merges two arrays of different types.
function mergeArrays<T, U>(arr1: T[], arr2: U[]): (T | U)[] {
return [...arr1, ...arr2];
}
/*
Example:
const numericArray = [1, 2, 3, 4, 5];
const stringArray = ['a', 'b', 'c', 'd', 'e'];
console.log(mergedArray);
Output: [1, 2, 3, 4, 5, 'a', 'b', 'c', 'd', 'e']
*/