0

I'm confused with typescript class, the private member doesn't work as it should.

class TClass {

  public pu = 1;
  private pv = 2

  constructor(private ar = 1) {

  }

}

const f1 = new TClass();
console.log({ ...f1 })

the output of this is

[LOG]: {
  "ar": 1,
  "pu": 1,
  "pv": 2
} 

as you can see all the private members are exposed!

but if I want to write a custom class I could use something like this

const JClass= function(ar=1){
  const pv=2;
  this.pu=1;
};

const f2= new JClass();
console.log({...f2})

and the output will be

[LOG]: {
  "pu": 1
} 

if you want to play here is a playground

so my question is how to make the typescript really respect the meaning of private?

Mohammad Hossein Amri
  • 1,842
  • 2
  • 23
  • 43
  • 1
    `private` just enforces the rules within ts. It will throw an error when you access it `f1.pv`. But, if you check the, transpiled javascript which ultimately runs in the browser, there is no difference between private and public properties. It is just another key on the object. (Yet: [Private class features](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/Private_class_fields)) – adiga Jul 20 '22 at 17:46
  • you can make properties private by using #: https://stackoverflow.com/questions/22156326/private-properties-in-javascript-es6-classes check this accepted answer – Dean Jul 20 '22 at 17:51

0 Answers0