title: TypeScript: interface method implementation
body: <p>How to implement a method in an interface in TypeScript?</p>
  
  <pre><code>interface Bar
  {
      num: number;
      str: string;
      fun?(): void;
  }
  class Bar
  {
      fun?()
      {
          console.log(this.num, this.str);
      }
  }
  let foo: Bar = {num: 2, str: "B"};
  foo.fun();
  </code></pre>
  
  <p>Expected: <code>2 B</code></p>
  
  <p>Actual:</p>
  
  <p><code>Error</code> <code>Cannot invoke an object which is possibly 'undefined'.ts(2722)</code></p>
  
  <p>If the optional flag is omitted from the method <code>fun()</code>, then the error will be:</p>
  
  <p><code>Property 'fun' is missing in type '{ num: number; str: string; }' but required in type 'Bar'.ts(2741)</code></p>
  
  <h1>Update 1</h1>
  
  <p>This is a work-around that results in what is expected, though it does not seem like the proper way to do this.</p>
  
  <pre><code>if(foo.fun)
  {
      foo.fun();
  }
  </code></pre>