Search⌘ K

Generic and Classes

Learn how to enhance your TypeScript classes with generics to create reusable, type-safe code. This lesson explains the concept of generics, their application in classes, and how they prevent type-related errors by maintaining type information throughout class usage. You will understand structural typing, interface use, and how generics provide a scalable solution to work with multiple types efficiently.

A simple class #

Engineers with an object-oriented background may associate the concept of generic with classes. It is a mechanism to generalize a class, to avoid duplicating the definition for each flavor of a class.

TypeScript 3.3.4
// Three classes
class Human {
public greeting: string = "Hello";
}
class Lion {
public greeting: string = "Grrrrrr";
}
class Tulip {
public greeting: string = "...";
}
class LivingSpecies_1 {
public species: Human;
constructor(species: Human) {
this.species = species;
}
public sayHello(): void {
console.log(this.species.greeting);
}
}
const species1 = new LivingSpecies_1(new Human());
species1.sayHello();

The code above might work even if we pass a different class object i.e. Lion or Tulip (which is not considered a good coding practice and may cause mayhem) to it because TypeScript is structural based and not nominal, which means it does not rely on the name but on the ...