CodePark/ questions / Access modifiers, readonly & statics
START PRACTICINGPRACTICE
Backend question · Object-oriented programming › Access modifiers, readonly & statics

This is compiled with TypeScript and run. What does it print?

class User {
  private password = "secret";
  #token = "t-123";
  name = "Ann";
}
console.log(JSON.stringify(new User()));
{"password":"secret","name":"Ann"}

It prints {"password":"secret","name":"Ann"}. TypeScript's private exists only at compile time. In the output it is a normal property, so JSON.stringify, Object.keys and logs all see it. A #token field is truly private at runtime, so it is not a property and is never included.

"
{"name":"Ann"}" is tempting, but private does not hide data at runtime. Never rely on it to keep secrets out of API responses or logs. Map to a response DTO instead.