app.ts 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. function startGame() {
  2. // Starting a new game.
  3. let playerName: string | undefined = getInputValue('playername');
  4. logPlayer(playerName);
  5. postScore(100, playerName);
  6. }
  7. function getInputValue(elementId: string): string | undefined {
  8. // Type assertions applies to the whole document.get...., not to document.
  9. // We know that we're only going to pass valid IDs, so will never get a null,
  10. // so we can assert the result will always be an input element.
  11. const inputElement: HTMLInputElement = <HTMLInputElement>document.getElementById(elementId);
  12. if (inputElement.value === '') {
  13. return undefined;
  14. }
  15. else {
  16. return inputElement.value;
  17. }
  18. }
  19. function postScore(score: number, playerName: string = 'MultiMath player'): void {
  20. let scoreElement: HTMLElement | null = document.getElementById('postedScores');
  21. scoreElement!.innerText = `${score} - ${playerName}`;
  22. }
  23. function logPlayer(name: string = 'MultiMath player'): void {
  24. console.log(`New game starting for player: ${name}.`);
  25. }
  26. function arm(doc: HTMLDocument) {
  27. // We know getElementById() cannot be null because we control the markup, so
  28. // we can use a non-null type assertion on the function call result.
  29. doc.getElementById('startGame')!.addEventListener('click', startGame);
  30. }
  31. arm(document);