app.ts 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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 logger: (value: string) => void;
  21. if (score < 0) {
  22. logger = logError;
  23. }
  24. else {
  25. logger = logMessage;
  26. }
  27. let scoreElement: HTMLElement | null = document.getElementById('postedScores');
  28. scoreElement!.innerText = `${score} - ${playerName}`;
  29. logger(`Score: ${score}`);
  30. }
  31. function logPlayer(name: string = 'MultiMath player'): void {
  32. console.log(`New game starting for player: ${name}.`);
  33. }
  34. function arm(doc: HTMLDocument) {
  35. // We know getElementById() cannot be null because we control the markup, so
  36. // we can use a non-null type assertion on the function call result.
  37. doc.getElementById('startGame')!.addEventListener('click', startGame);
  38. }
  39. arm(document);
  40. const logMessage = (message: string) => console.log(message);
  41. function logError(message: string): void {
  42. console.error(message);
  43. }
  44. let myResult: Result = {
  45. playerName: 'Marie',
  46. score: 5,
  47. problemCount: 5,
  48. factor: 7,
  49. };
  50. let player: Person = {
  51. name: 'Daniel',
  52. formatName: () => 'Dan',
  53. };