Generic and Classes
This lesson delves into making classes more reusable with generic types.
We'll cover the following...
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.
Press + to interact
// Three classesclass 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 ...