TypeScript子类使用private继承父类触发2415错误的原因及解决方案咨询
Let's break down your TypeScript issue and answer each of your questions clearly:
1. Why can't I use private in this scenario?
TypeScript's private modifier enforces strict encapsulation: private members are exclusively owned by the class they're declared in, and are completely invisible to subclasses. When you declare a private bar in both Baz and Foo, you're actually creating two entirely separate, unrelated properties—one belonging to Baz, another to Foo.
TypeScript checks that a subclass correctly extends its parent class, and having duplicate private member declarations breaks this contract. The compiler sees that Foo has a private bar that doesn't align with Baz's private bar, hence the TS2415 error.
Put simply: Your Foo class isn't extending Baz's bar—it's creating its own, which conflicts with the parent class's private member.
2. Is there a way to use private in this scenario?
Yes, but it depends on your goal:
If you want
Footo reuseBaz's private member: You can't. Sinceprivatemembers are inaccessible to subclasses, you can't reference or re-declare them inFoo. Instead, changeBaz'sbartoprotected(which allows subclasses to access it) if you wantFooto interact with that member.If you need
Footo have its own private member: Rename the subclass's private member to avoid the name conflict. For example:class Bar {} class Baz { constructor(private bar: Bar) {} } class Foo extends Baz { // Use a unique name for the subclass's private member constructor(private _bar: Bar) { super(_bar); } }This works because
Baz'sbarandFoo's_barare now distinct private members with no overlap.
3. Is public a suitable replacement for private?
It depends on your encapsulation needs:
If you want
barto be accessible from outside the class: Then yes,publicworks. But this breaks encapsulation if your original intent was to keepbarinternal to the class hierarchy.If you want to keep
barencapsulated within the class hierarchy:publicis not a good replacement. Instead, use theprotectedmodifier forBaz'sbar. This lets subclasses likeFooaccess the member while keeping it hidden from external code:class Bar {} class Baz { constructor(protected bar: Bar) {} } class Foo extends Baz { constructor(bar: Bar) { super(bar); // Now Foo can access this.bar directly } }This maintains proper encapsulation while resolving the inheritance conflict.
内容的提问来源于stack exchange,提问作者Jon Sud

