I have interface :
export interface IFieldValue {
name: string;
value: string;
}
And I have class that implements it :
class Person implements IFieldValue{
name: string;
value: string;
constructor (name: string, value: string) {
this.name = name;
this.value = value;
}
}
after reading this post I've thinking about refactoring :
class Person implements IFieldValue{
constructor(public name: string, public value: string) {
}
}
Question : In first class I have fields which by default should be as private
. In second sample I can only set them as public
. Is it all correct or my understanding of default Access modifiers in TypeScript?
In following definition
Attributes
<Person>.name
and<Person>.value
are public by default.as they are here
Beware: Here is an incorrect way of doing it, since
this.name
andthis.value
will be regarded as not defined in the constructor.To make these attributes private you need to rewrite it as
or equivalently
which in my opinion is the most preferable way that avoids redundancy.