title: document.getElementById("id") may be null
body: <p>Edit: I'm using TypeScript v2.2.1</p>
  
  <p>I am new to TypeScript and I'm not sure what the cleanest way of dealing with DOM elements that may or may not exist is.  Basically, I want to check whether an element exists, and then if it does, add an event listener to it (I have <code>--strict_null_checks</code> turned on).</p>
  
  <p>When I do it the JS-like way:</p>
  
  <pre class="lang-js prettyprint-override"><code>const myElement = document.getElementById('my-id');
  if (myElement) {
    myElement.addEventListener('click', (e:Event) =&gt; {
      // Do stuff.
    });
  }
  </code></pre>
  
  <p>I get the error <code>my_script.ts(3, 3): error TS2531: Object is possibly 'null'.</code></p>
  
  <p>I can get around this by using a not-null assertion:</p>
  
  <pre><code>const maybeMyElement = document.getElementById('my-id');
  if (maybeMyElement) {
    const myElement = maybeMyElement!;
    myElement.addEventListener('click', (e:Event) =&gt; {
      // Do stuff.
    });
  }
  </code></pre>
  
  <p>But my understanding is that those sorts of assertions are generally frowned upon, and aesthetically, I don't like creating twice as many variables.</p>
  
  <p>Is there a cleaner way to do this?</p>