public: The Default Visibility
You'll learn that class members in TypeScript are publicly accessible by default, and what adding the public keyword explicitly actually does.
The Default: Everything Is Public
When you create properties or methods in a TypeScript class without any visibility modifier, they are automatically public. This means they can be accessed from anywhere: inside the class, by subclasses, or from external code using an instance.
TypeScript follows JavaScript's default behavior here—since JavaScript doesn't have built-in visibility restrictions (historically), everything is accessible everywhere by default.
Explicit public Is Redundant (But Valid)
You can write public explicitly before a property or method, but it's essentially documenting what's already true:
class User {
name: string; // public by default
public age: number; // explicitly public (same effect)
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
greet() { // public by default
return `Hello, I'm ${this.name}`;
}
public farewell() { // explicitly public
return "Goodbye!";
}
}
const user = new User("Alice", 30);
console.log(user.name); // ✓ Works (public)
console.log(user.age); // ✓ Works (public)
console.log(user.greet()); // ✓ Works (public)
Both name and age are public. Both greet() and farewell() are public. The keyword changes nothing about behavior.
Why Use public Explicitly?
Most TypeScript developers omit public since it's the default. However, you might see it used for:
- Consistency: If a class mixes visibility levels, some teams write
publiceverywhere for visual clarity - Documentation: Making intent explicit, especially when teaching or in heavily commented code
- Parameter properties: When using the shorthand syntax in constructors (though still optional)
Key Takeaway: Class members are public by default in TypeScript; writing public explicitly is optional and changes nothing—it just makes the default visible in your code.