typescript
/

TypeScript Access Modifiers

Last Sync: Today

On this page

10
0%
5 min read
Remaining
5 minleft

Click any section to jump — progress syncs automatically

typescript

TypeScript Access Modifiers

What are Access Modifiers?

Access modifiers control the visibility and accessibility of class properties and methods in TypeScript.

Types of Modifiers

ModifierAccess Level
publicAccessible everywhere
privateAccessible only within class
protectedAccessible within class and subclasses

Public Example

TypeScriptRead-only
1
class User {
  public name: string = 'John';
}

Private Example

TypeScriptRead-only
1
class User {
  private age: number = 30;
}

Protected Example

TypeScriptRead-only
1
class Person {
  protected id: number = 1;
}

class Employee extends Person {
  getId() {
    return this.id;
  }
}

Constructor Shortcut

TypeScriptRead-only
1
class User {
  constructor(public name: string, private age: number) {}
}

Encapsulation

Access modifiers help achieve encapsulation by hiding internal implementation details and exposing only necessary data.

Best Practices

  • Use private for sensitive data
  • Use protected for inheritance scenarios
  • Keep public API minimal
  • Use constructor shorthand for cleaner code

Common Mistakes

  • Overusing public properties
  • Not using private when needed
  • Confusing protected with private
  • Exposing internal logic unnecessarily

Conclusion

Access modifiers improve code security and maintainability by controlling visibility within TypeScript classes.

Try it yourself

class User { constructor(private age: number) {} }

Test Your Knowledge

Q1
of 3

Private means?

A
Global
B
Class only
C
Subclass
D
Public
Q2
of 3

Protected access?

A
Everywhere
B
Only class
C
Class + subclass
D
None
Q3
of 3

Default modifier?

A
private
B
protected
C
public
D
none

Frequently Asked Questions

What is public?

Accessible everywhere.

What is private?

Accessible only inside class.

What is protected?

Accessible in class and subclasses.

Previous

ts classes

Next

ts inheritance

Related Content

Need help?

Explore our comprehensive docs or start a chat with our tech experts.