All CategoriesFull stack Web Development

Access Modifiers and Keywords of TypeScript

TypeScript supports new features in JavaScript, like support for class-based object-oriented programming. Like in the other object oriented programming language as Java, C++ we got access modifier of public, protected, private which helps us to encapsulate our class and makes the code visibility mode very limited.
Similarly, Typescript supports few of the object-oriented programming methodology to make the data and methods more encapsulated.

Understanding The Usage of Public Access Modifier in Class

The public access modifier helps to share the class field data member and member methods visible outside the class area. If we haven’t specified our class field as public, private or protected the by default specifier of our class members is public.
Let demonstrate a small example. See the below image.

Here we have created a Collage class with a constructor and a few public fields. Notice that classes field name doesn’t contain any access modifier, and roll_no contains public access modifier which letting the programmer decide on the right level of abstraction. The name field by default access modifier is public, so if we don’t specify any access modifier it will be public in nature.
Public keyword makes our class field less restrictive and accessible outside the class. Our data member and member methods can be extended and can be used in other class as well.
After we saved our file in our project folder as Collage.ts. Here in our example, we have specified our folder name as below image view down:

Inside samplecode folder, we have created Collage.ts you can look down the project structure codes.

The code on the left hand side of the folder we got some few sample codes which we have created along with Collage.ts.
Now we have to type in the terminal to make this Collage.ts compile
tsc Collage.ts
/*Once it got compiled we can generate Collage.js as we can see in our project folder available */
tsc  -w

tsc  -w watches all the ts codes. Meaning it keeps an eye on it and watches for any change made in the ts file it will automatically be reflected in .js file as well. So the above image makes watching for file changes. If we make any change it will start and the file will be detected.
Now you can view the Collage.js and this we will copy it and paste in the browser console to get our output.  

Now copy this and paste in the browser console.

See the output we got as well.
Explanation: When the constructor is created the object is initialized, and public access modifier data get accessed by the constructor field and constructor of a class got called by the object implicitly. Coming from Java will help you to understand easily.
What happens if we change the access modifier from public to private in all fields of our class?

The red line in the object creation suggest there is an error as :[ts] Constructor of class ‘Collage’ is private and only accessible within the class declaration
constructor Collage(name: any, roll_no: any): Collage
So, it is restricted not to use constructor as private and if we have made our data members as private it will be accessible within a class. It can’t be extended outside the class area.
What happens if we use the static keyword with public access modifier in class data member?
static  public roll_no:number;

As you see in the above code, inside the Collage class we used static before the public collagename:String=”Acadgild”. It gives us red line which is an error in our online compiler typescript playground.
Error:‘public’ modifier must precede ‘static’ modifier.
It means we can’t write static first then public however the opposite is possible.

No red underline comes.
Static keyword usage
In an object oriented programming language like in JAVA, we got static keyword which is a non-access modifier. Here in Typescript, we don’t have any non-access modifiers kind of up concept although we also got static keyword which supports similar terminologies.
The example will help you to understand the static keyword.

In the above example let keyword is used to define blocked level variable and the value prints.
If you notice using the class name the method is been called or bound. Similar concepts you will find in another object oriented programming language as the class name will help to call the method because static keyword method is liable to class not to instances of a class.

And the value prints as Sachin.
Time for an experiment. Suppose we call a static method of a class with the class it’s class name then Is there a need for creating the instance of the class?

Here in the above code, we removed the instance of the class. And answer prints.

So, it’s proved if we have static methods in a class and we don’t want to create an object I mean the instance of a class the program will work.
If we have nonstatic data member and a static method, and we want to print a nonstatic data to inside a static method it won’t accept and error we will get ce:can’t find the value.

You see there is red color marked error line shows in our above code which tells ce: can’t find name1.
In short, we can’t pass non-static data member to a static method of a class.

Let’s move ahead and see “interface and class “with using public access modifier example.

Here we’re going to create a Student class with a constructor and a few public fields. Notice that classes and interfaces play well together, letting the programmer decide on the right level of abstraction.
Also of note, the use of public on arguments to the constructor is a shorthand that allows us to automatically create properties with that name.

The output we get it after running as:
So, interface data member without implements we have accessed in our student class.
Usually, interface data and methods are abstracted by default

therefore, we need a class to implement the interface properties. But if we don’t write still it works as:

No red underline. Which makes code works.  
Notes:”Don’t write any access modifier in interface properties “ if we write we will get the error :”modifier can’t appear on a type member”.

Class Inheritance extends and super keyword use along with protected and private keyword restriction.

Super keyword is used in a class inherit the base class data members constructors or methods.
extends keyword is used to extends from base class properties to the child class.
If we make our base class data member and constructor, methods as private it can’t able to inherit it will be accessed within a class.
protected keyword is similar to private however it is less restrictive and makes our code only accessible to the immediately derived class.
Let’s take an example to understand:

Let us see the output as:

The code in the above having two classes with a base class and child class.
Class Animal contains protected field data member as a name which can be accessed or can be extended by the derived class.  
Note: “It is very important to include super keyword in our derived class while extending the base class” if we don’t do it will throw an error as :”

Error : constructor for derived classes must contain a super call”.
As we see in the above if we remove super(); it gives red underline.

Here in the above code gives error as we made our Animal class data member batch_id as private and tried to access outside in the snakes class which extends an animal class.
Error: “Property ‘batch_id’ is private and only accessible within class ‘animal’.
(property) animal.batch_id: number”
Error : ‘super’ must be called before accessing ‘this’ in the constructor of a derived class.
this: this
We also made the constructor of the base class animal as private and that also gives error as :
Error:  “Cannot extend a class ‘animal’. Class constructor is marked as private. class animal “
Therefore, these are the restriction while working with access modifier in typeScript.
Stay tuned to AcadGild for more interesting blogs.

Som

is a full-stack web developer, designer, and educator who has been building user interfaces for over a decade. He’s done work for Fortune 4 companies, national political campaigns, and international technology leaders. His proudest achievement is helping people learn full-Stack web development.

2 Comments

  1. Informative and nice blog you have shared on access modifiers ‘ public access modifier’ well explained. I have never gone through ‘ interface and class ‘ using public access modifier, here you provided a vital information. Thanks a lot for sharing!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Related Articles

Close
Close