EDIT: This seems to be a known issue in Typescript. The solution was implemented , but eventually pulled out due to insoluble performance problems.
This situation often arises in our code base:
function consumer<T>(valueProducer: () => T) {
let value = valueProducer();
console.log(value);
}
class Foo {
private _value: number = 100;
getValue(): number {
return this._value;
}
constructor() {
consumer(this.getValue);
}
}
The solution in Typescript is either:
consumer( () => this.getValue() ); // capture correct this
Or that:
consumer( this.getValue.bind(this) ); // bind to correct this
This problem may be obvious to the Typescript / Javascript programmer, but our team transfers most of C # to Typescript, and in C # this is not an error (i.e. the passed method in C # is automatically connected to passers-by). Therefore, I would like the type system to detect this error, if possible.
The first, obvious step for explicit input thisused for the callback:
function consumer<T>(valueProducer: (this: void) => T) {
let value = valueProducer();
console.log(value);
}
, , , , this Foo:
class Foo {
getValue(this: Foo): number {
return this._value;
}
, :
error TS2345: Argument of type '(this: Foo) => number' is not assignable to parameter of type '(this: void) => number'.
The 'this' types of each signature are incompatible.
Type 'void' is not assignable to type 'Foo'.
this: this . this ? , ?
(plunker )