# Classes & Visibility

> Public, Private, and Protected modifiers.

Subject: TypeScript | Lesson 42 of 54 | 4 min read
Interactive lesson: https://codewithanimation.in/typescript/classes-and-visibility
Previous: [The Awaited Type](https://codewithanimation.in/typescript/awaited-type.md) | Next: [Parameter Properties](https://codewithanimation.in/typescript/parameter-properties.md)

## 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

```typescript
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!
```

## Common mistake: The Runtime Illusion

TypeScript's `private` keyword is an illusion. It *only* exists during compile time. When compiled to JavaScript, the property is fully exposed!

If you need actual runtime privacy, you must use the native JavaScript `#` prefix (e.g., `#token: string;`), which is strictly enforced by the JavaScript engine at runtime.

## Tip: Parameter Properties

Instead of declaring a property and assigning it in the constructor, you can do it all at once:

`constructor(public name: string, private token: string) {}`

This is a massive boilerplate saver!

## Try it: 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.

The animation is on the lesson page and is not part of this text version: https://codewithanimation.in/typescript/classes-and-visibility

## Check yourself

### Question 1

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

- A. There is no difference.
- B. `private` is enforced at runtime, `#` is only enforced at compile time.
- C. `#` provides hard runtime privacy, `private` only provides compile-time checks.

Correct answer: C

TypeScript's 'private' keyword is stripped away during compilation, offering no runtime protection. The '#' syntax is a native JavaScript feature that provides true, hard privacy at runtime.

## 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.
