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);
The explaination of this article are really clear and nice, so I took it[1]
Typescript has
TWO
ways to declare variables.Method 1
Method 2
Both lead to the same function. And obviously, the second is better.
Here above is for the
private
, therefore, for thepublic
, it works in the same way. It means that accessing from the outside of this class is possible.Conclusion
We have a complete example for illustration. Check the three variables and see how it works.
References:
[1] https://kendaleiv.com/typescript-constructor-assignment-public-and-private-keywords/