Be careful with mixing TypeScript and JavaScript
In TypeScript you can use the same private class features like in JavaScript since ES2021.
So far so good.
Depending on the compiler options target during compiling TS to JS there might be added some generated JS-code to handle private
-fields in JS and this needs to be remembered when modifying these fields!
There might be getter and setter helpers for the private
-fields like __classPrivateFieldGet()
and __classPrivateFieldSet()
.
So what happens if you use this code:
Object.assign(this.#myprivate, {});
The generated JS-code might look like:
Object.assign(__classPrivateFieldGet(this, _MyClass_myprivate, "f"), {});
So the assignment will not be directly on the #myprivate
.
Solution number 1 (not preferable)
const myprivate = this.#myprivate;
this.#myprivate = Object.assign(myprivate, {});
Here we assign to a local scope const and afterwards the new value is set by __classPrivateFieldSet()
. So #myprivate
is fine.
But assign
has been only one sample, so the better solution might be to not use object and prototype manipulation in JS-style or check the generated JS for the targeted purpose.
Solution number 2 (preferable)
Use the more idiomatic TypeScript way with spread operator. For objects this is available since ES2018.
So the TS-code
this.#config_app = { ...this.#config_app, {} };
becomes in JS
__classPrivateFieldSet(this, _MyClass_myprivate, {
...__classPrivateFieldGet(this, _MyClass_myprivate, "f"), {}
}, "f");