Skip to main content

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 public modifier 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(); // accessible

public properties and methods can be freely read, changed and called from outside the class.


3. Access inside and outside the class

Where you access fromAccess to public
Inside the classYes
In a subclassYes
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); // Tim

TypeScript automatically creates the fields name and age and 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

ModifierVisibilityUsable outside the class?
publicEverywhereYes
privateOnly inside the classNo
protectedIn the class and subclassesNo

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 ready
Premium

A concise answer to help you respond confidently on this topic during an interview.