Skip to content

Opt-in flag for strictThisChecks #16615

Closed
@EliSnow

Description

@EliSnow

TypeScript Version: 2.3.4

Code
This is a repro of an actual bug that bit me which I was surprised the type checker did not catch.

class Foo {
    constructor(private name: string) { }
    public bar(s: string) {
        return this.name + s;
    }
}

const foo = new Foo("f");
["a", "b"].map(foo.bar);

Expected behavior:
The type checker should catch that bar will be called with a this of undefined (assuming strict mode). Methods should have an implicit this of the containing class (in this case this: Foo), or at least an interface with the properties accessed within the method (this: { name: string }).

Actual behavior:
No compile error is emitted and a runtime error is the result.

In #14936, @RyanCavanaugh mentions there being a performance cost to adding in implicit this types. At least in my case, since I was bit by this, I would be willing to pay the extra cost during compile to catch these kind of errors. Perhaps a compiler option would be worthwhile.

Metadata

Metadata

Assignees

No one assigned

    Labels

    In DiscussionNot yet reached consensusSuggestionAn idea for TypeScript

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions