Home > Articles > Web Development

  • Print
  • + Share This
From the author of

Interfaces and Structural Typing

The final class to create is DiceRoller, which will start a timer and roll the dice each time the timer interval has passed. I’m going to use this class to demonstrate a couple of features that you’ll use in many larger applications: interfaces and structural typing. You’ll use these features often when your application reads data from a web service. That data will often be delivered in JSON format, and JavaScript will interpret that data as an anonymous object. You can define a TypeScript interface to work with those objects. TypeScript supports structural typing, which means that the anonymous objects represented by the JSON data don’t need to declare that they support a particular interface. The objects only need to have the correct properties.

In the example, I’ll define an IRoll interface, which happens to be implemented by the DiceRollTurn class. The DiceRoller class will use the IRoll interface rather than the DiceRollTurn class definition, except when creating a new object.

The only members needed on the IRoll interface are the two properties to display a roll (check out branch 13-defineIRollInterface). These properties match the members defined in the DiceRollTurn class:

interface IRoll {
   totalValue: number;
   displayHTML: HTMLDivElement;
}

The DiceRoller class will reference and use that interface in its data members (check out branch 14-basicDiceRollerConstructor):

/// <reference path="iroll.ts" />
class DiceRoller {
   element: HTMLElement;
   allRolls: Array<IRoll>;
   timerToken: number;

   constructor(element: HTMLElement) {
     this.element = element;
     this.allRolls = new Array<IRoll>();

   }
}

Notice that the array of rolls is both strongly typed and generic: It’s an array of objects in which each object implements the IRoll interface.

The remaining implementation for the DiceRoller class uses features I’ve already discussed. You can grab the master branch from the repository to see the final code.

  • + Share This
  • 🔖 Save To Your Account