# Access Modifiers & readonly — TypeScript

Source: https://www.geekswithgeeks.com/en/typescript/ts-access-modifiers-implements

> Control visibility with public, private and protected.

## public / private / protected

`public` (default) is visible everywhere, `private` only inside the class, `protected` inside the class and its subclasses.

```typescript
class Account {
  public owner: string;
  private balance: number;

  constructor(owner: string, balance: number) {
    this.owner = owner;
    this.balance = balance;
  }
}

const acc = new Account("Ada", 500);
console.log(acc.balance);
// Error: Property 'balance' is private and only accessible within class 'Account'.
```

## Parameter properties

Adding a modifier directly to a constructor parameter declares **and** assigns the property in one step.

```typescript
class Account {
  constructor(
    public owner: string,
    private balance: number,
    readonly openedOn: Date = new Date()
  ) {}
}
// equivalent to writing the fields + this.x = x manually
```

## readonly on class fields

A `readonly` field can be set in the constructor but never reassigned afterward — good for IDs and creation timestamps.

**Quiz:** Which modifier allows access from a subclass but not from outside code?

- [ ] public
- [ ] private
- [x] protected

*Answer:* protected. protected members are visible in the declaring class and its subclasses, but not to outside code.
