puddlejumper26 / blogs

Personal Tech Blogs
4 stars 1 forks source link

Why defining Variables inside constructor of TS #61

Open puddlejumper26 opened 4 years ago

puddlejumper26 commented 4 years ago

The explaination of this article are really clear and nice, so I took it[1]

Typescript has TWO ways to declare variables.

Method 1

class SampleClass{
     private name: string;

     constructor(name:string){
          this.name = name;
     }
}

Method 2

class SampleClass{
    constructor(private name: string) { }
}

Both lead to the same function. And obviously, the second is better.

Here above is for the private, therefore, for the public, it works in the same way. It means that accessing from the outside of this class is possible.

class SampleClass{
   constructor(public age: number){ }
}

Conclusion

We have a complete example for illustration. Check the three variables and see how it works.

class SampleClass{
   constructor( name: string, private height: number; public age: number){ }

   sampleMethod( ){
        console.log(this.name); // Compiler error: Property 'name' does not exist on type 'SampleClass'.
        console.log(this.height);
        console.log(this.age);
  }
}

const samplePerson = new SampleClass('Obiwan', 180, 50);

samplePerson.sampleMethod( );

console.log(samplePerson.name); // Compiler error: Property 'name' does not exist on type 'SampleClass'.
console.log(samplePerson.height); // Compiler error: 'height' is private and only accessible within class 'SampleClass'.
console.log(samplePerson.age);

References:

[1] https://kendaleiv.com/typescript-constructor-assignment-public-and-private-keywords/