Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change visibilty in child class

Tags:

typescript

It appears that it is possible to change property visibility in child class from protected to public:

class BaseFoo  {
    protected foo;
}

class Foo extends BaseFoo {
   foo = 1;
}

new Foo().foo;

But not in any other possible combination. I believe that accidental change to public by omitting visibility modifier is more harmful than changing from protected to private (which isn't allowed).

What is the explanation for that? Is it a known issue?

like image 572
Estus Flask Avatar asked Jan 23 '26 00:01

Estus Flask


1 Answers

It looks like the question has been discussed, and then closed as "working as intended", in the repo here. OOP theory is a bit beyond my expertise, but my understanding of the maintainer's logic is that protected is the category of methods that should be private on the base class, but are allowed to be public on children. Then

class Foo extends BaseFoo {
   protected foo = 1;
}

is the way to keep foo "private" on Foo. As to the question of implicit property types (should foo = 1 default to public?), that seems to make sense as the expected behavior. Defaulting to public is the standard throughout TS, and if you want to make that not possible, you'd use:

class BaseFoo  {
    private foo;
}

class Foo extends BaseFoo {
   foo = 1; // compiler error
}
like image 100
Jack Koppa Avatar answered Jan 24 '26 23:01

Jack Koppa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!