Skip to content

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

Closed
@panthus

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.

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