Skip to content

this in methods not type of enclosing class #14936

@EricTetz

Description

@EricTetz

TypeScript Version: 2.2.1

Code

function consumer(valueProducer: (this: void) => number) {
    console.log(valueProducer());
}

class Foo {
    private _value: number = 100;

    // this method requires `this: this` or `this: Foo` to provide type safety
    getValue(): number {
        return this._value;
    }

    constructor() {
        // callback does not have `this: void`, but Typescript can't warn me
        consumer(this.getValue);
    }
}

Expected behavior:

Class methods default to this: this.

Actual behavior:

Class methods default to this: any?

I'm not familiar with Git so I'm not good at distinguishing discussions vs actually implemented code, but #6739 appears to address the problem directly and includes the line:

"if --strictThis is specified, then functions will default this: void and methods will default this: this."

Which is exactly what I want. However, that page has an edit saying that the feature was "removed from this release". That was over a year ago. Was a fix reintroduced somewhere else? Catching this error seems like exactly the thing you'd want a type system for.

Metadata

Metadata

Assignees

No one assigned

    Labels

    QuestionAn issue which isn't directly actionable in code

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions