Home > database >  Class 'Foo' incorrectly extends base class 'Baz' with private keyword
Class 'Foo' incorrectly extends base class 'Baz' with private keyword

Time:03-21

I got a typing error that says:

Class 'Foo' incorrectly extends base class 'Baz'.
  Types have separate declarations of a private property 'bar'.(2415)
class Bar {}

class Baz {
  constructor(private bar: Bar) {}
}

class Foo extends Baz {
  constructor(private bar: Bar) {
    super(bar);
  }
}

When I change private to public it's okay, but why? Why can't I use private? Is there a way to use private? Is public a good alternative to private?

CodePudding user response:

So, let's start by typing the "extended" version of what you wrote:

class Bar {}

class Baz {
    private bar: Bar;

    constructor(bar: Bar) {
        this.bar = bar;
    }
}

class Foo extends Baz {
    private bar: Bar;

    constructor(bar: Bar) {
        this.bar = bar;
        super(bar);
    }
}

As you can see you're defining a private attribute with the same name in both your parent and child class. What you want to do is probably this:

class Bar {}

class Baz {
    protected bar: Bar;

    constructor(bar: Bar) {
        this.bar = bar;
    }
}

class Foo extends Baz {
    constructor(bar: Bar) {
        super(bar);
    }
}

That using the "short" version became:

class Bar {}

class Baz {
    constructor(protected bar: Bar) {}
}

class Foo extends Baz {
    constructor(bar: Bar) {
        super(bar);
    }
}
  • Related