TypeScript has lot of useful features not available in JavaScipt which helps in developing complex applications.One such feature is Automatic Assignment of Constructor Parameters in TypeScript .This is also called Parameter Property.
TypeScript automatically manages the class variables when we have constructor arguments.When we declare a class we normally declare variables and constructor arguments separately.We declare a class as:
class Employee { _name:string; _id:string; _age:number; constructor(Name: string, Id: string,Age:number) { this.Name = _name; this.Id = _id; this.Age=_age; } }
This is common pattern whether we are using C# ,Java or any other programming language.
But when we declare parameters in TypeScript with some access modifier such as private then TypeScript handles the parameter differently.TypeScript automatically generates new variable for the constructor arguments.Equivalent code using the automatic parameter assignment will be
class Employee { constructor(private Name: string, private Id: private string,Age:number) { } }
This TypeScript constructor will create three new instance members corresponding to the three constructor arguments.The three instance variables will be initialized with the values of the three constructor arguments.This feature called Parameter properties helps solve the common problem when we need to declare and initialize instance variables separately.
The modifiers which we can use for Parameter properties are:
- public
- protected
- readonly