Typescript Class Constructor Parameter Declarations | Task

Ole Ersoy
Oct - 09  -  1 min

Scenario

We went to avoid assigning parameters within the typescript class constructor like this:

constructor(p:number) {
   this.p = p
}

Approach

Declare the property within the constructor using a modifier (public, private, protected):

class Test1 {
    constructor(
      public p1:string;
      public p2:string;
 ) {}
}

console.log(new Test1('1', '2'));

If we don't use a modifier that property assignment does not take place and we get an empty object.

class Test2 {
  constructor(p1: string, p2: string) {}
}
//Properties are missing
console.log(new Test2('1', '2'));

Demo