0

I reproduced in the code below an issue i have when working with private properties in typescript.

Expected behaviour: only the public properties should be visible in my object output like in normal encapsulation.

my goal here is to make the property with setter and getter a part of the exposed api of my class rather than the private property (like in C#)

 class MyClass {
      public otherProp: boolean;

      constructor() {
          this.otherProp = false;
          this._privateProp = false;
      }

      private _privateProp: boolean;

      get publicProp() : boolean {
        return this._privateProp;
      }

      set publicProp(values : boolean) {
          this._privateProp = values;
      }

    }

    let x: MyClass = new MyClass();

    console.log(x); // MyClass {otherProp: false, _privateProp: false}
                   // Expected output: MyClass {otherProp: false, publicProp: false}
mehdi Ichkarrane
  • 396
  • 5
  • 10

1 Answers1

0

You use # to mark properties as private:

class MyClass {
      public otherProp: boolean;

      constructor() {
          this.otherProp = false;
          this.#_privateProp = false;
      }

      #_privateProp: boolean;

      get publicProp() : boolean {
        return this.#_privateProp;
      }

      set publicProp(values : boolean) {
          this.#_privateProp = values;
      }

    }

    let x: MyClass = new MyClass();

    console.log(x); // MyClass {otherProp: false}
Ibraheem
  • 2,168
  • 20
  • 27
  • Thanks for your response, i didn't know about private property marker. but i m looking for a way to make the public getter setter visible too (like in my example), unfortunately in js i can't use the same name for getter/setter and the property – mehdi Ichkarrane Jun 07 '20 at 22:04