Skip to content

Inheritance and type narrowing prevent private member access in base class. #11454

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
panthus opened this issue Oct 7, 2016 · 4 comments
Closed
Labels
Bug A bug in TypeScript
Milestone

Comments

@panthus
Copy link

panthus commented Oct 7, 2016

TypeScript Version: 2.0.3

Code

class Animal {
    private sound: string;

    public makeSound() {
        if (this instanceof Cat || this instanceof Dog) {
            this.sound = "grr"; // Errors
        }
    }
}

class Cat extends Animal {
    public walk() {}
}

class Dog extends Animal {
    public eat() {}
}

Expected behavior:
Should be able to access private member in its declaring class.

Actual behavior:
Cannot access private member in its declaring class if the subclasses have different members and we narrow the type of this to a union type of its subclasses.

@RyanCavanaugh RyanCavanaugh added the Bug A bug in TypeScript label Oct 7, 2016
@falsandtru
Copy link
Contributor

I think this narrowed by subclasses should have external accessibility of them. So I think this is a correct behavior.

@normalser
Copy link

I think it should work. Works in Java. https://goo.gl/Pb5p2Y

@mhegazy
Copy link
Contributor

mhegazy commented Dec 14, 2016

So we should narrow to Cat & Animal | Dog & Animal ?

@mhegazy mhegazy added this to the Future milestone Dec 14, 2016
@sandersn sandersn removed their assignment Jan 7, 2020
@jakebailey
Copy link
Member

Just looking at old bugs; this one was fixed in 3.9+ via #38277, though I'm not sure that the PR actually introduces a test for this particular case (though the underlying thing is in fact the same; this is narrowed to (this & Cat) | (this & Dog)).

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

7 participants