Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the equivalent of protected in TypeScript?

Tags:

typescript

What is the equivalent of protected in TypeScript?

I need to add some member variables in the base class to be used only in derived classes.

like image 307
Tahereh Farrokhi Avatar asked Mar 07 '13 15:03

Tahereh Farrokhi


People also ask

What is protected in TypeScript?

protected implies that the method or property is accessible only internally within the class or any class that extends it but not externally. Finally, readonly will cause the TypeScript compiler to throw an error if the value of the property is changed after its initial assignment in the class constructor.

Does TypeScript have protected?

TypeScript supports three access modifiers - public, private, and protected.

What is protected access modifier in TypeScript?

Protected. A Protected access modifier can be accessed only within the class and its subclass. We cannot access it from the outside of a class in which it is containing.

What is public/private protected in TypeScript?

TypeScript provides three access modifiers to class properties and methods: private , protected , and public . The private modifier allows access within the same class. The protected modifier allows access within the same class and subclasses. The public modifier allows access from any location.


1 Answers

Updates

November 12th, 2014. Version 1.3 of TypeScript is available and includes the protected keyword.

September 26th, 2014. The protected keyword has landed. It is currently pre-release. If you are using a very new version of TypeScript you can now use the protected keyword... the answer below is for older versions of TypeScript. Enjoy.

View the release notes for the protected keyword

class A {     protected x: string = 'a'; }  class B extends A {     method() {         return this.x;     } } 

Old Answer

TypeScript has only private - not protected and this only means private during compile-time checking.

If you want to access super.property it has to be public.

class A {     // Setting this to private will cause class B to have a compile error     public x: string = 'a'; }  class B extends A {     method() {         return super.x;     } } 
like image 179
Fenton Avatar answered Sep 27 '22 19:09

Fenton