- Touring the Template Application
- Building Your Own Types
- Creating Multiple Types and Interfaces
- Interfaces and Structural Typing
- Why Should You Use TypeScript?
Creating Multiple Types and Interfaces
Large programs require multiple types. Multiple types and interfaces, often created by different team members, introduce communication errors into our JavaScript programs.
As I walk through the rest of the example code, I’ll concentrate less on the implementation of a single class, more on how multiple classes interact and how TypeScript supports that interaction.
The next class to build will be the type that represents a single roll of two dice. The DiceRollTurn class contains two Die objects and computes the total of the two dice. When you create the class in Visual Studio, you can just declare the members; you get IntelliSense on the Die objects, and the class builds without errors. The Visual Studio project structure knows about the types defined in any of the TypeScript files in the project.
class DiceRollTurn { firstDie = new Die(); secondDie = new Die(); }
However, if you built the project from the command line, the DiceRollTurn class wouldn’t compile. You inform the TypeScript compiler (and other external tools) about the Die class by including a reference comment:
/// <reference path="die.ts" />
Now the command-line static analysis tools understand what a Die object is and what the valid operations are.
To finish the class definition, I’ll add two public members and implement the constructor so that all the members are initialized correctly (check out branch 11-finishDiceRollTurn):
class DiceRollTurn { firstDie = new Die(); secondDie = new Die(); public totalValue: number; public displayHTML: HTMLDivElement; constructor() { this.totalValue = this.firstDie.dieRoll + this.secondDie.dieRoll; this.displayHTML = document.createElement("div"); var span = document.createElement("span"); span.innerHTML = "Total roll" + this.totalValue; this.firstDie.dipslayDieInContainer(this.displayHTML); this.secondDie.dipslayDieInContainer(this.displayHTML); this.displayHTML.appendChild(span); } }
If you read the above code carefully, you’ll notice that earlier, I had misspelled displayDieInContainer (as dipslayDieInContainer) when I created that method. In TypeScript, I can use refactoring tools to change the name in the Die class definition or at either call site, and the name change will be carried over to all other references. Just highlight the function name, press F2, and edit the name, and all the changes are made. Most importantly, it’s not a text replace; it’s a semantic code change (check out branch 12-fixSpellingError).