title: Ensure object type in TypeScript
body: <p>I'm using TypeScript for the browser.  I find myself writing a lot of code like this:</p>
  <pre><code>const button = document.getElementById(id);
  if (!(button instanceof HTMLButtonElement)) {
    throw new Error(&quot;TODO -- insert better error message here&quot;);
  }
  button.disabled = false;
  </code></pre>
  <p>The <code>throw</code> is required.  getElementById() returns type <code>HTMLElement | null</code>, which does not support the disabled property.  After the <code>throw</code> the type correctly changes to <code>HTMLButtonElement</code>.  I could have done this with a type assertion, but this code also includes a runtime check.</p>
  <p>Is there any way to move this into a function?  Something like:</p>
  <pre><code>const button = verify(document.getElementById(id), HTMLButtonElement);
  button.disabled = false;
  </code></pre>
  <p>or</p>
  <pre><code>const button = verify&lt;HTMLButtonElement&gt;(document.getElementById(id));
  button.disabled = false;
  </code></pre>
  <p>But not</p>
  <pre><code>const button = verify&lt;HTMLButtonElement&gt;(document.getElementById(id), HTMLButtonElement);
  button.disabled = false;
  </code></pre>
  <p>because then I'm typing the same word twice and I could easily make a mistake.</p>
  <p>In Java or C# I'd say <code>(HTMLButtonElement)document.getElementById(id)</code> instead of <code>verify()</code>.  In C++ I'd say <code>dynamic_cast&lt; HTMLButtonElement &amp; &gt;(document.getElementById(id))</code>.  Again, I'm trying to do the runtime check and satisfy compiler.  And I want to avoid as much typing as possible.</p>