title: How to track whether a function can throw in TypeScript?
body: <p>The <a href="https://rustwasm.github.io/2018/09/26/announcing-web-sys.html#the-js-sys-crate-is-100-feature-complete" rel="nofollow noreferrer">announcement for <code>js-sys</code></a> said:</p>
  
  <blockquote>
    <p>We considered a TypeScript frontend, but did not prioritize it because TypeScript does not describe whether or not functions throw exceptions</p>
  </blockquote>
  
  <p>1) Is this correct?
  2) If not, what are the ways to mark whether functions can throw in TS? Are there ways the compiler can help?</p>
  
  <p>Here are two solutions. The first does not actually check the types, but they are at least visible as a way to communicate with other programmers. The second way does some limited checking, but has a minor run-time cost and requires manual effort.</p>
  
  <pre><code>// unchecked solution
  type OrThrow&lt;T&gt; = T;
  
  function add(a: number, b: number): OrThrow&lt;number&gt; {
      return a + b;
  }
  
  // checked solution with run-time cost and manual work
  type Exn&lt;T&gt; = T &amp; { __canThrow: true };
  
  function exn&lt;T&gt;(t: T): Exn&lt;T&gt; {
      return t as Exn&lt;T&gt;;
  }
  
  function sum(a: number, b: number): Exn&lt;number&gt; {
      return exn(a + b);
  }
  </code></pre>