Sub topic 6
Controlling access: public, private, and protected
This chapter assumes you can write a basic TypeScript class with fields, a constructor, and methods, and that you know extends at a conceptual level. Here you will learn what the three access modifiers allow, where they apply, and the mistakes people commonly make with them. Later chapters cover private and protected in more detail.
What access modifiers do
An access modifier is a keyword placed before a class member (a field, method, or accessor). It tells the compiler which code may reference that member. There are three:
public: any code can use the member.protected: the declaring class and its subclasses can use the member.private: only the declaring class can use the member.
Modifiers let you separate a class's public contract from its internal details. If outside code can only reach the public members, you can change the rest without breaking callers.
| Modifier | Inside the declaring class | Inside a subclass | Outside code |
|---|---|---|---|
| `public` | Allowed | Allowed | Allowed |
| `protected` | Allowed | Allowed | Error |
| `private` | Allowed | Error | Error |
The three modifiers together
class Session {
public userId: string;
protected createdAt: Date;
private token: string;
constructor(userId: string, token: string) {
this.userId = userId;
this.createdAt = new Date();
this.token = token;
}
isSameToken(other: Session): boolean {
return this.token === other.token;
}
}
class AdminSession extends Session {
ageInMs(): number {
return Date.now() - this.createdAt.getTime(); // OK: protected
// return this.token.length;
// Error: Property 'token' is private and only accessible within class 'Session'.
}
}
const s = new Session("u1", "abc");
console.log(s.userId); // u1
// console.log(s.createdAt);
// Error: Property 'createdAt' is protected and only accessible within class 'Session' and its subclasses.
// console.log(s.token);
// Error: Property 'token' is private and only accessible within class 'Session'.Three details in this example are easy to miss:
isSameTokenreadsother.token. Privacy is per class, not per instance, so oneSessioncan read anotherSession's private fields. Many languages work this way.AdminSessioncan readcreatedAtthroughthis, but nottoken.- The errors appear only at the points where outside code touches the members.
public is the default
If you write no modifier, the member is public. Writing public explicitly changes nothing at runtime or in the types. Teams differ on whether to write it. Some prefer it for clarity, and others omit it to reduce noise. Follow your project's lint rules, and be consistent.
Changing visibility in a subclass
A subclass may make an inherited member more visible, but not less visible. This follows from substitutability: code that holds a Base must be able to treat a Derived as a Base.
class Base {
protected greet(): string {
return "hi";
}
}
class Derived extends Base {
public override greet(): string {
return "hello"; // OK: protected widened to public
}
}
console.log(new Derived().greet()); // hello
class Open {
public ping(): void {}
}
// class Closed extends Open {
// private ping(): void {}
// }
// Error: Class 'Closed' incorrectly extends base class 'Open'.You can widen protected to public, but you cannot narrow public to private or protected. A common reason to widen is to expose a hook that the base class kept internal.
Compile-time only
Access modifiers are checked by the TypeScript compiler and then erased. The emitted JavaScript has ordinary properties with no protection. Two consequences follow:
- Code that bypasses the type system can read "private" members. Examples are
as any, plain JavaScript callers, and the debugger. - Bracket notation with a string literal is deliberately allowed by the compiler as an escape hatch.
class Vault {
private secret = "s3cret";
}
const v = new Vault();
console.log(v["secret"]); // s3cret: allowed by the compiler
console.log(JSON.stringify(v)); // {"secret":"s3cret"}The JSON.stringify line is the more serious one. A private field is still an own property, so serializing the object, logging it, or spreading it into another object includes the value. Do not rely on private to protect real secrets. If you need runtime enforcement, use ECMAScript #private fields, which a later chapter covers.
Common errors
- Reaching into a private member from a subclass. If a subclass needs a member, declare it
protected. Do not make itpublicjust to silence the error. - Making everything
public. This removes the benefit of modifiers. Start withprivate, then widen only when a real caller needs access. - Making a member
privateand then trying to override it. A subclass cannot declare a member with the same name as a base-classprivatemember. The compiler reports that the class incorrectly extends its base class, because the types become incompatible. - Assuming
protectedallows access through any instance. Inside a subclass, you can access a protected member only through an instance of that subclass (or one of its subclasses), not through a plain base-class instance.
class Animal {
protected name = "animal";
}
class Dog extends Animal {
sameName(other: Dog): boolean {
return this.name === other.name; // OK: other is a Dog
}
// compareToAnimal(other: Animal): boolean {
// return this.name === other.name;
// // Error: Property 'name' is protected and only accessible
// // through an instance of class 'Dog'.
// }
}
console.log(new Dog().sameName(new Dog())); // trueChoosing a modifier
Ask who needs the member, then pick the narrowest modifier that works:
- Callers outside the class need it:
public. - Only subclasses need it, as a hook or shared state:
protected. - Only this class needs it:
private.
Keep in mind that protected extends your class's API surface to every subclass author, so it is a commitment you must maintain. A private member can be renamed or removed freely, which is why it is usually the safer default.
Exercise
Given class A { private x = 1; protected y = 2; public z = 3; } and class B extends A { read() { return [this.x, this.y, this.z]; } }, which expression causes a compile error, and what is the smallest change to the declaration of A that fixes it without making the member public?
Show answer
this.x causes the error, because x is private and only accessible within class A. Changing private x to protected x fixes it, since B can read protected members through this.
Exercise
A base class declares public save(): void. A subclass declares protected save(): void. Does this compile? Explain why in one sentence.
Show answer
No. A subclass cannot narrow a member's visibility, because code holding a base-class reference must still be able to call save() on a subclass instance.