title: Typescript: Inference of "this" with higher order functions
body: <p>When I define a function in an object literal, Typescript will correctly identify the type of <code>this</code>, e.g.:</p>
  
  <pre class="lang-js prettyprint-override"><code>const test = {
    foo: function() {
      return { type: 'foo' }
    },
    bar: function() {
      // Usage of "this" is fine for Typescript.
      return { type: 'bar', foo: this.foo() }
    }
  }
  </code></pre>
  
  <p>This breaks when I use a higher order function to wrap the function:</p>
  
  <pre class="lang-js prettyprint-override"><code>// Some HOC passing through the "this" parameter.
  function cacheValue&lt;THIS, RESULT&gt;(
    factory: (this: THIS) =&gt; RESULT
  ): (this: THIS) =&gt; RESULT {
    let instance: RESULT | undefined
    return function() {
      if (instance === undefined) {
        instance = factory.call(this)
      }
      return instance
    }
  }
  
  const testHOC = {
    foo: function() {
      return { type: 'foo' }
    },
    bar: cacheValue(function() {
      // error TS2571: Object is of type 'unknown'.
      return { type: 'bar', foo: this.foo() }
    })
  }
  </code></pre>
  
  <p>Now Typescript incorrectly identifies the type of <code>this</code> in the function as <code>unknown</code>, so the call to <code>this.foo()</code> is an error: <code>error TS2571: Object is of type 'unknown'.</code></p>
  
  <p>Is there a way to get this to work </p>
  
  <ul>
  <li>without explicitly defining the type of <code>testHOC</code> (i.e. writing an interface), and</li>
  <li>without using an arrow function and referring to <code>testHOC</code> directly (because I might want to replace <code>testHoc.foo</code> later)?</li>
  </ul>