Typescript: implicit type `this` for class methods

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() {
        // Oops! Inside consumer(), getValue will be called with wrong this
        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 { // I could also have written getValue(this: this)
        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 )

+4
1

this , javascript, map, this:

function consumer<T>(valueProducer: () => T, thisArg: any) {
    let value = valueProducer.apply(thisArg);
    console.log(value);
}

class Foo {
    private _value: number = 100;

    getValue(): number {
        return this._value;
    }

    constructor() {
        consumer(this.getValue, this);
    }
}

, , .

0

Source: https://habr.com/ru/post/1672943/


All Articles