app.ts 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. function startGame() {
  2. // Starting a new game.
  3. let playerName: string = 'Audrey';
  4. logPlayer(playerName);
  5. const messagesElement: HTMLElement | null = document.getElementById('messages');
  6. // We know messagesElement cannot be null because we control the markup, so
  7. // we can use a non-null type assertion
  8. const element = messagesElement!;
  9. element.innerText = 'Welcome to MultiMath! Starting a new game';
  10. console.log('Starting new game');
  11. }
  12. function logPlayer(name: string) {
  13. console.log(`New game starting for player: ${name}.`);
  14. }
  15. function arm(doc: HTMLDocument) {
  16. // We know getElementById() cannot be null because we control the markup, so
  17. // we can use a non-null type assertion on the function call result.
  18. doc.getElementById('startGame')!.addEventListener('click', startGame);
  19. }
  20. arm(document);
  21. // Type assertions (not casting, more like in Go).
  22. let value: any = 42;
  23. let fixedString1: string = (<number>value).toFixed(2);
  24. let fixedString2: string = (value as number).toFixed(2);
  25. console.log(value, fixedString1, fixedString2);
  26. /**
  27. * y is now optional, while x is not.
  28. */
  29. function foo(x: number, y?: string): string {
  30. return x.constructor.toString() + y;
  31. }
  32. foo(2, "3");
  33. foo(2);
  34. function bar(...args: number[]) {
  35. console.log(args.reduce((accu: number, curr: number) => accu + curr, 0));
  36. }
  37. bar(1, 2, 3, 4, 5); // (5+6)/2 = 15
  38. // Rejected because of noImplicitAny.
  39. // function qux(x, y) { return x + y; }
  40. // qux('a', 'b');
  41. function sendGreeting(greeting: string = "Hello, world"): void {
  42. console.log(greeting);
  43. }
  44. sendGreeting();
  45. sendGreeting("Hello, moon");