镜像站点 · 本页由第三方 GitHub 只读镜像提供,非 GitHub 官方站点,不接受任何登录或凭据输入。前往 github.com
Skip to content

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

Closed

Description

@panthus

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.

Activity

  1. falsandtru commented on Oct 9, 2016

    @falsandtru
    Contributor

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

  2. normalser commented on Oct 9, 2016

    @normalser

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

  3. mhegazy commented on Dec 14, 2016

    @mhegazy
    Contributor

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

  4. added this to the milestone on Dec 14, 2016
  5. jakebailey commented on Jul 6, 2023

    @jakebailey
    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)).

  6. locked as resolved and limited conversation to collaborators on Oct 21, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    BugA bug in TypeScript

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions