Skip to content

Class method with this typing cannot access private or protected members #13815

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
krryan opened this issue Feb 1, 2017 · 1 comment
Closed
Labels
Bug A bug in TypeScript
Milestone

Comments

@krryan
Copy link

krryan commented Feb 1, 2017

TypeScript Version: 2.2.0-dev.20170116

Code

class Foo {
    constructor(
        protected bar: string | null,
        protected baz: number
    ) {}

    doThing(this: Foo & { bar: string }) {
        return this.bar.length > 0 ? this.baz : -1;
    }
}

Expected behavior:
Compiles without error.

Actual behavior:

Property 'baz' does not exist on type 'Foo & { bar: string; }`.

Notably, though, even if baz is public, attempting to use doThing here even from within another method fails:

class Foo {
    constructor(
        protected bar: string | null,
        public baz: number
    ) {}

    doThingIfYouCan() {
        if (this.bar != null) {
            return this.doThing(); // error here
        }
    }

    doThing(this: Foo & { bar: string }) {
        return this.bar.length > 0 ? this.baz : -1;
    }
}

Here the error is

The 'this' context of type 'this' is not assignable to method's 'this' of type 'Foo & { bar: string; }'.
[...]
Property 'bar' is protected in 'Foo' but public in type '{ bar: string; }'.

This is a very similar problem, where the this typing on doThing requires that bar is public even though both canDoThing and doThing should have access to it.

My use-case here is that I have a method that is currently only being called in non-null cases, and only makes sense to call in non-null cases, so I'm currently throwing in a null case (that should never happen). But I would like to enforce that at compile time.

@mhegazy mhegazy added the Bug A bug in TypeScript label Feb 1, 2017
@mhegazy mhegazy added this to the TypeScript 2.9 milestone Apr 12, 2018
@mhegazy mhegazy modified the milestones: TypeScript 3.0, Future Jul 2, 2018
@sandersn sandersn removed their assignment Jan 7, 2020
@jakebailey
Copy link
Member

This issue had the same root cause as #11454 and is now fixed in TS 3.9+ (see linked issue).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Bug A bug in TypeScript
Projects
None yet
Development

No branches or pull requests

4 participants