TypeScript Public and Private
What
Before JavaScript standardized the # syntax, TypeScript introduced its own private, protected, and public keywords for controlling member visibility.
How
You add the keyword before the property or method name. By default, all class members are public:
class SecretAgent {
private id: string; // TypeScript-only privacy
constructor(id: string) {
this.id = id;
}
}
Why
The private keyword is only enforced by the TypeScript compiler; at runtime, the property is still accessible in plain JavaScript. While the native # syntax is now generally preferred, the private keyword is still common in older codebases or when targeting environments that don’t support modern JavaScript features.
Summary
While private and public keywords are useful, prefer the native # syntax for true runtime privacy.