Saturday, April 8, 2017

getsetters in TypeScript

The following code will barf up an alert telling you that "The Green Anaconda is 5 meters long!"

class Snake {
   private _commonName: string;
   private _lengthInMeters: number;
   get commonName(): string {
       return this._commonName;
   }
   set commonName(c: string) {
       this._commonName = c;
   }
   get lengthInMeters(): number {
       return this._lengthInMeters;
   }
   set lengthInMeters(l: number) {
       this._lengthInMeters = l;
   }
}
let anaconda = new Snake();
anaconda.commonName = "Green Anaconda";
anaconda.lengthInMeters = 5;
let prose = `The ${anaconda.commonName} is ${anaconda.lengthInMeters} meters
      long!`;
alert(prose);

No comments:

Post a Comment