Browse Source

3.8: more non-null type assertions.

Frederic G. MARAND 5 years ago
parent
commit
49b64dab7e
1 changed files with 8 additions and 10 deletions
  1. 8 10
      app/app.ts

+ 8 - 10
app/app.ts

@@ -3,11 +3,11 @@ function startGame() {
   let playerName: string = 'Audrey';
   logPlayer(playerName);
 
-  const messagesElement: HTMLElement|null = document.getElementById('messages');
-  if (messagesElement === null) {
-    return;
-  }
-  messagesElement.innerText = 'Welcome to MultiMath! Starting a new game';
+  const messagesElement: HTMLElement | null = document.getElementById('messages');
+  // We know messagesElement cannot be null because we control the markup, so
+  // we can use a non-null type assertion
+  const element = messagesElement!;
+  element.innerText = 'Welcome to MultiMath! Starting a new game';
   console.log('Starting new game');
 }
 
@@ -16,11 +16,9 @@ function logPlayer(name: string) {
 }
 
 function arm(doc: HTMLDocument) {
-  const startGameButton: HTMLElement|null = doc.getElementById('startGame');
-
-  if (startGameButton) {
-    startGameButton.addEventListener('click', startGame);
-  }
+  // We know getElementById() cannot be null because we control the markup, so
+  // we can use a non-null type assertion on the function call result.
+  doc.getElementById('startGame')!.addEventListener('click', startGame);
 }
 
 arm(document);