Friday, December 29, 2017

getting started with generics in TypeScript

where T : Whatever style C# generics have a sister in TypeScript. This will throw up an alert with "ROAR" in it!

class Cat {
   private _speech: string;
   constructor (speech: string) {
      this._speech = speech;
   }
   speak():string{
      return this._speech;
   }
}
class Housecat extends Cat {
   constructor() {
      super("meow");
   }
}
class Lion extends Cat {
   constructor() {
      super("ROAR");
   }
}
class CatOwner<T extends Cat> {
   pet: T;
}
let catOwner: CatOwner<Lion> = new CatOwner<Lion>();
catOwner.pet = new Lion();
alert(catOwner.pet.speak());

No comments:

Post a Comment