Skip to main content

Access Modifiers

TypeScript natively injects rigid Object-Oriented concepts like Encapsulation deep down into JavaScript classes via specific modifiers: public, private, and protected.

1. public​

The default behavior. Any property strictly labeled public can be accessed and modified natively from entirely outside the class anywhere in the application.

2. private​

A property denoted as private can strictly ONLY be read or changed by methods operating inside the exact class it was constructed on.

3. protected​

Similar to private, but an inherited "Child" class (extends) is legally permitted to access the internal property.

class Account {
public username: string; // Readable everywhere
protected balance: number = 0; // Readable internally by Account AND child classes
private secureId: number; // Readable ONLY by Account

constructor(user: string, id: number) {
this.username = user;
this.secureId = id;
}
}

class PremiumAccount extends Account {
addFunds(amount: number) {
// Legal! Because balance is 'protected'
this.balance += amount;

// ERROR! secureId is completely 'private' and invisible to children
// console.log(this.secureId);
}
}

const myAcc = new Account("Alice", 1234);
console.log(myAcc.username); // Works
// console.log(myAcc.balance); // ERROR! Protected property cannot be externally pinged

Shorthand Parameter Initialization​

Writing complex constructors allocating 15 parameters sequentially gets remarkably tedious. TypeScript offers a fantastic shorthand! Modifiers injected straight into the constructor arguments automatically create properties bound to the class instance!

class Product {
// These behave as fully-mapped properties! No separate mapping inside the body needed!
constructor(
public name: string,
private cost: number,
readonly uuid: string
) {}
}

const keyboard = new Product("Mechanical Keyboard", 50, "x71o");