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
you could use the get keyword to define your dumpLog() method as an accessor.
Instead of answering you directly, try understanding this:
In the above code, the
MyClass
has a private propertyx
. ThecreateClass
function returns a new classMySubClass
that extendsMyClass
and tries to access the private propertyx
. This results in a TypeScript errorTS2341: 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 havecreateClass
return an object that implements that interface instead of returningMySubClass
directly. Here’s the updated code:In this updated code, we define an interface
MyClassInterface
that only exposes the publicgetValue()
method ofMyClass
. ThecreateClass
function now returns an object that implements this interface, and uses an instance ofMyClass
to get the value ofx
and return it. This way, the private propertyx
is not exposed outside ofMyClass
, and the returned object only has access to the publicgetValue()
method.