What does the public access modifier do?
The public modifier in TypeScript is the most open access level.
It makes a property or method accessible from anywhere:
- from inside the class,
- from its subclasses,
- and from outside, through an instance of the class.
1. Syntax
javascript
class User {
public name: string;
public constructor(name: string) {
this.name = name;
}
public greet(): void {
console.log(`Hello, ${this.name}!`);
}
}The
publicmodifier can be omitted, it is the default.
2. Usage example
javascript
class User {
public name: string;
public age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
public greet() {
console.log(`Hi, I'm ${this.name}, ${this.age} years old.`);
}
}
const user = new User("Tim", 25);
user.name = "Alex"; // accessible
user.greet(); // accessiblepublic properties and methods can be freely read, changed and called from outside the class.
3. Access inside and outside the class
| Where you access from | Access to public |
|---|---|
| Inside the class | Yes |
| In a subclass | Yes |
| Outside (via an instance) | Yes |
4. The public modifier in constructor parameters
A shorthand declaration:
javascript
class User {
constructor(public name: string, public age: number) {}
}
const u = new User("Tim", 30);
console.log(u.name); // TimTypeScript automatically creates the fields
nameandageand assigns them the passed values.
5. Everything is public by default
If you do not specify a modifier, the behavior is the same:
javascript
class User {
name: string; // this is public by default
greet() {}
}6. Comparison with other modifiers
| Modifier | Visibility | Usable outside the class? |
|---|---|---|
| public | Everywhere | Yes |
| private | Only inside the class | No |
| protected | In the class and subclasses | No |
Summary
public:
- Is accessible everywhere (inside, outside, in subclasses);
- Is used by default;
- Can be placed before properties, methods and constructor parameters;
- Lets you explicitly mark a class member as part of the class's public interface.
Simple way to remember it:
public= "accessible to everyone".
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.