Yes in Typescript we can do that I mean we can add access modifiers in Constructor Function along with the parameters to control the access throughout out the class.
If you see in the last tutorial I have given details all you needs know about access modifier from typescript, if you have not checked yes please do it is essential here is the link
What is Access Modifiers and how to use Access Modifiers in TypeScript ?
As you start growing TypeScript Developer or essentially a Javascript Developer you should start making habit of using best practices it will help you to be expert developer.
Table of Contents
Constructor Function without Access Modifiers
Typescript has a very good feature of removing redundant code of lines and refactoring it, so if you see the following typescript class we added two private variables and similarly we have two parameters for the constructor to assign variables.
Refactoring TypeScript class by adding Access Modifiers
Now let’s see how to refactor the above class by adding Access Modifiers in constructor parameters.
You can go ahead and remove variable declaration from the line number 2 and 3 and prefix the constructor parameters with access modifiers and also remove initialization from the body of constructor function, like showing below:
Now if you see the class it looks much clean and simple to read if you compile above class and using typescript compiler at end typescript compiler will generate assigning part and declaration of this fields out of the box.
I have both the class here for your reference.
Original Typescript class:
Compiled typescript class into javascript:
Conclusion:
As a developer It is alway good to use best practices into your programming everyday it will help you grow fast and achieve your target on time.
IMPORTANT NOTE – Before you go and read another tutorial I want to clarify one important thing here about adding modifiers in Constructor Function, no matter what access modifier you want to apply to the variables you have to prefix those with the modifiers, even for default public modifier.
For example if you decide to add public modifier even the default access is public you should still needs mention that in the Constructor otherwise your code will not work.
So from now always keep in mind to utilize this feature from Typescript to save your time as well as make you typescript code more clean, easy to maintain and read.