Learning navigation

Code with Animation

Classes & Visibility

Public, Private, and Protected modifiers.

TypeScript4 min readConcept 42 of 54

Object-Oriented Encapsulation

TypeScript provides class visibility modifiers:

public (default) - accessible anywhere.

protected - accessible within the class and subclasses.

private - accessible only within the class.

Hiding State

Visibility modifiers help you hide internal implementation details.

If you have a DatabaseConnection class, you shouldn't let outside code directly mutate the connectionString or socket properties. You mark them as private to force usage through safe methods.

Syntax

class User {
  public name: string;
  private token: string;

  constructor(name: string, token: string) {
    this.name = name;
    this.token = token;
  }
}

const user = new User("Alice", "secret123");
console.log(user.name); // OK
// console.log(user.token); // TypeScript Error!

Try it

Attempt to access a private property versus a #private property from outside the class. Observe how the compiler reacts compared to the actual JavaScript runtime engine.

class User {
public name = "Alice";
private token = "abc-123";
#secret = "super-secure";
}

// Outside the class...
const user = new User();
console.log(user.name);
TypeScript Compiler
No errors
JavaScript Runtime
>"Alice"

Check yourself

Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.

  1. 1What is the difference between `private x` and `#x` in a TypeScript class?

Remember this

  • public, protected, and private control access levels.
  • These modifiers only exist at compile time in TypeScript.
  • For strict runtime privacy, use the native JS # syntax.
  • Parameter properties in constructors save a lot of boilerplate.

Done with this concept?

Mark it complete to track your progress. No login needed.