It can be cumbersome to always set values from the constructor to a field. A possibility is to assign the field directly from the constructor signature into the class:
class MyClass3{ public constructor(private p1:number, public p2:string){} } const myClass3 = new MyClass3(1, "2"); console.log(myClass3.p2);
By setting the visibility of the encapsulation of each parameter of the constructor, a member is created with the same type. In the preceding example, two fields are created for the class with the name and the type of the parameter. The following code is exactly the same as the previous example, which is heavier in terms of definition and assignation:
class MyClass3Same { private p1: number; public p2: string; public constructor(p1: number, p2: string) { this.p1 = p1; this.p2 = p2; } } const myClass3Same = new MyClass3Same (1, "2"); console.log(myClass3.p2);