Skip to content

Instantly share code, notes, and snippets.

@mojaray2k
Last active May 24, 2020 18:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mojaray2k/e184a79475841a73625f7c10737472de to your computer and use it in GitHub Desktop.
Save mojaray2k/e184a79475841a73625f7c10737472de to your computer and use it in GitHub Desktop.
Using Generics in Typescript
class ArrayOfNumbers {
constructor(public collection: number[]) {}
get(index: number): number {
return this.collection[index];
}
}
class ArrayOfStrings {
constructor(public collection: string[]) {}
get(index: number): string {
return this.collection[index];
}
}
class ArrayOfAnything<T> {
constructor(public collection: T[]) {}
get(index: number): T {
return this.collection[index];
}
}
// Array of strings
new ArrayOfAnything<string>(['a', 'b', 'c']);
// Array of Numbers
new ArrayOfAnything<number>([1, 2, 3]);
// Example of generics with functions
function printStrings(arr: string[]): void {
for (let i = 0; i < arr.length; i++) {
console.log(arr[i]);
}
}
function printNumbers(arr: number[]): void {
for (let i = 0; i < arr.length; i++) {
console.log(arr[i]);
}
}
function printAnything<T>(arr: T[]): void {
for (let i = 0; i < arr.length; i++) {
console.log(arr[i]);
}
}
// Print an array of strings
printAnything<string>(['a', 'b', 'c']);
// Print an array of numbers
printAnything<number>([1, 2, 3]);
// Generic Constraints
class Car {
print() {
console.log('I am a car');
}
}
class House {
print() {
console.log('I am a house');
}
}
interface Printable {
print(): void;
}
function printHousesOrCars<T extends Printable>(arr: T[]): void {
for (let i = 0; i < arr.length; i++) {
arr[i].print();
}
}
// Print array of houses
printHousesOrCars<House>([new House(), new House()]);
// Print array of cars
printHousesOrCars<Car>([new Car(), new Car()]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment