title: Implicit `this` type for class methods
body: <p>EDIT: It appears this is a known issue in Typescript. A <a href="https://github.com/Microsoft/TypeScript/pull/6739" rel="nofollow noreferrer">solution was once implemented</a> but ultimately pulled because of unresolvable performance problems. </p>
  
  <p>This situation comes up often in our codebase:</p>
  
  <pre><code>function consumer&lt;T&gt;(valueProducer: () =&gt; T) {
      let value = valueProducer();
      console.log(value);
  }
  
  class Foo {
      private _value: number = 100;
  
      getValue(): number {
          return this._value;
      }
  
      constructor() {
          // Oops! Inside consumer(), getValue will be called with wrong this
          consumer(this.getValue);
      }
  }
  </code></pre>
  
  <p>The solution in Typescript is either this:</p>
  
  <pre><code>consumer( () =&gt; this.getValue() ); // capture correct this
  </code></pre>
  
  <p>Or this:</p>
  
  <pre><code>consumer( this.getValue.bind(this) ); // bind to correct this
  </code></pre>
  
  <p>This problem might be obvious to a Typescript/Javascript programmer, but our team is porting a large body of C# to Typescript, and in C# this is <em>not</em> an error (i.e. a passed method in C# is automatically bound to the object instance). So I'd like the type system to catch this error, if possible.</p>
  
  <p>The first, obvious step to explicitly type the <code>this</code> used on the callback:</p>
  
  <pre><code>function consumer&lt;T&gt;(valueProducer: (this: void) =&gt; T) {
      let value = valueProducer();
      console.log(value);
  }
  </code></pre>
  
  <p>I would expect that to be enough, but it turns out I also need to explicitly type the <code>this</code> parameter on the Foo method:</p>
  
  <pre><code>class Foo {
      getValue(this: Foo): number { // I could also have written getValue(this: this)
          return this._value;
      }
  </code></pre>
  
  <p>With these two things in place, I now get exactly the error I want:</p>
  
  <pre><code>error TS2345: Argument of type '(this: Foo) =&gt; number' is not assignable to parameter of type '(this: void) =&gt; number'.
    The 'this' types of each signature are incompatible.
      Type 'void' is not assignable to type 'Foo'.
  </code></pre>
  
  <p>However, I don't want to have to add <code>this: this</code> to every method in my app. Shouldn't the value of <code>this</code> in a method implicitly be that of the enclosing type? Is there another way to achieve this same result without adding all that boilerplate noise to my classes?</p>
  
  <p>(<a href="https://plnkr.co/edit/4PZfHi87qXjBkonMYTux?p=info" rel="nofollow noreferrer">plunker for discussed code</a>)</p>