Sub topic 2
Public, Private, and Controlled Class APIs
Assume you know basic TypeScript types, functions, objects, and the this keyword. This chapter focuses on how visibility and controlled access shape a class API.
`public`: the default visibility
A public member can be accessed wherever the object is available. Writing public is optional because class members are public by default.
`private`: hiding implementation details
A private member is accessible only inside its declaring class. Callers use public methods or accessors instead of changing internal state directly. TypeScript checks this restriction during compilation.
`readonly` properties
A readonly property can be assigned during initialization, usually in the constructor, but cannot be reassigned afterward. This protects the property reference itself. It does not make nested objects deeply immutable.
Parameter properties
A parameter property declares and initializes a field directly in the constructor parameter list. Modifiers such as public, private, and readonly determine the resulting field's visibility.
class Account {
private constructor(
public readonly id: string,
private currentBalance: number
) {}
static empty(id: string): Account {
return new Account(id, 0);
}
deposit(amount: number): void {
if (amount <= 0) {
throw new Error("Amount must be positive");
}
this.currentBalance += amount;
}
get balance(): number {
return this.currentBalance;
}
set balance(value: number) {
if (value < 0) {
throw new Error("Balance cannot be negative");
}
this.currentBalance = value;
}
}
const account = Account.empty("a-1");
account.deposit(50);
account.balance = 125;
console.log(account.id, account.balance); // a-1 125Getters and setters
A getter lets callers read a value using property syntax, such as account.balance. A setter lets callers assign through property syntax while validation remains inside the class. A getter without a setter creates a read-only public property.
Static members and private constructors
A static member belongs to the class itself, not to each instance. Call it as Account.empty(...). A private constructor prevents callers from using new Account(...). Together, they let the class control how instances are created, often through named factory methods.
Exercise
Why can code call account.deposit(50) but not directly assign account.currentBalance?
Show answer
deposit is public by default, while currentBalance is private and accessible only inside Account.