Why is my private field in the output?
TypeScript private controls ordinary access during type checking. Its modifier disappears, leaving an ordinary field that JSON.stringify includes in this example.
A JavaScript #private field is not an ordinary property and is omitted here. Pick server response fields explicitly. Neither private form makes shipped browser secrets safe. This example has no custom toJSON method.
Understand it. Then fix it.
Private controls type checking.
TypeScript private stops ordinary outside access during type checking. But the private word disappears from the JavaScript. The field stays.
// Emitted JavaScript
class Box {
code = "demo";
}JSON can still see that field.
JavaScript Object Notation, or JSON, is a text format for data. Stringify includes ordinary fields like code by default. That is why code appears in the text. This example has no custom toJSON method.
JSON.stringify(new Box());
// {"code":"demo"}Hash fields stay private at runtime.
Yes. The hash creates a JavaScript private field. It is not an ordinary property. With the same stringify call, this example becomes an empty object.
class Box {
#code = "demo";
}
JSON.stringify(new Box());
// {}For server output, pick the fields.
For a response sent by your server, explicitly choose what you send. Neither private form makes secrets safe in browser code. Code delivered to the browser is available to the user. Explicit output shape · no client-side secret storage.
const payload = { id: record.id };
JSON.stringify(payload);Code blocks are teaching excerpts. Keep the surrounding error handling and application requirements.
Save the code excerpts ↓Read the full transcript
Why does a TypeScript private field show up when I turn this object into text? TypeScript private stops ordinary outside access during type checking. But the private word disappears from the JavaScript. The field stays. JavaScript Object Notation, or JSON, is a text format for data. Stringify includes ordinary fields like code by default. That is why code appears in the text. Does a hash field behave differently? Yes. The hash creates a JavaScript private field. It is not an ordinary property. With the same stringify call, this example becomes an empty object. For a response sent by your server, explicitly choose what you send. Neither private form makes secrets safe in browser code. Code delivered to the browser is available to the user. My privacy policy was one word. The compiler deleted it.