skip to Main Content

I wonder why I cannot define private members for my returned class that is generated with the below function. Does anyone know why it could not be private and protected? I saw this code somewhere but in his VS code I did not see any error but it does in my VS code.

function myLoggerClass() {
  return  class Logger {
    private completeLog: string = "";
    log(str: string) {
      console.log(str);
      this.completeLog += `${str}n`;
    }
    dumpLog() {
      return this.completeLog;
    }
  }
}

The error says :

Errors in code
Property 'completeLog' of exported class expression may not be private or protected.

2

Answers


  1. you could use the get keyword to define your dumpLog() method as an accessor.

    get dumpLog() {
      return this.completeLog;
    }
    
    Login or Signup to reply.
  2. Instead of answering you directly, try understanding this:

    class MyClass {
      private x: number = 42;
    }
    
    function createClass(): typeof MyClass {
      return class MySubClass extends MyClass {
        constructor() {
          super();
          console.log(this.x); // Error: Property 'x' is private and only accessible within class 'MyClass'
        }
      };
    }
    

    In the above code, the MyClass has a private property x. The createClass function returns a new class MySubClass that extends MyClass and tries to access the private property x. This results in a TypeScript error TS2341: Property 'x' is private and only accessible within class 'MyClass'..

    One solution is to define an interface that exposes the public properties and methods of MyClass, and have createClass return an object that implements that interface instead of returning MySubClass directly. Here’s the updated code:

    class MyClass {
      private x: number = 42;
      
      getValue(): number {
        return this.x;
      }
    }
    
    interface MyClassInterface {
      getValue(): number;
    }
    
    function createClass(): MyClassInterface {
      return {
        getValue: () => {
          const obj = new MyClass();
          return obj.getValue();
        }
      };
    }
    
    const myObject = createClass();
    console.log(myObject.getValue()); // Output: 42
    

    In this updated code, we define an interface MyClassInterface that only exposes the public getValue() method of MyClass. The createClass function now returns an object that implements this interface, and uses an instance of MyClass to get the value of x and return it. This way, the private property x is not exposed outside of MyClass, and the returned object only has access to the public getValue() method.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search