Browse Source

3.7: type assertions, strictNullChecks for null/undefined.

Frederic G. MARAND 5 years ago
parent
commit
73d99ed771
2 changed files with 21 additions and 3 deletions
  1. 20 3
      app/app.ts
  2. 1 0
      tsconfig.base.json

+ 20 - 3
app/app.ts

@@ -1,9 +1,12 @@
 function startGame() {
   // Starting a new game.
-  const playerName: string = 'Audrey';
+  let playerName: string = 'Audrey';
   logPlayer(playerName);
 
-  const messagesElement: HTMLElement = document.getElementById('messages');
+  const messagesElement: HTMLElement|null = document.getElementById('messages');
+  if (messagesElement === null) {
+    return;
+  }
   messagesElement.innerText = 'Welcome to MultiMath! Starting a new game';
   console.log('Starting new game');
 }
@@ -12,4 +15,18 @@ function logPlayer(name: string) {
   console.log(`New game starting for player: ${name}.`);
 }
 
-document.getElementById('startGame').addEventListener('click', startGame);
+function arm(doc: HTMLDocument) {
+  const startGameButton: HTMLElement|null = doc.getElementById('startGame');
+
+  if (startGameButton) {
+    startGameButton.addEventListener('click', startGame);
+  }
+}
+
+arm(document);
+
+// Type assertions (not casting, more like in Go).
+let value: any = 42;
+let fixedString1: string = (<number>value).toFixed(2);
+let fixedString2: string = (value as number).toFixed(2);
+console.log(value, fixedString1, fixedString2);

+ 1 - 0
tsconfig.base.json

@@ -10,6 +10,7 @@
 
     /* Strict Type-Checking Options */
     "noImplicitAny": false,
+    "strictNullChecks": true,
 
     /* Additional Checks */
     "noUnusedLocals": true