Getters and Setters with Different Access
You'll learn how to create asymmetric property access where everyone can read a value, but only internal code can modify it.
What Are Asymmetric Getters and Setters?
In TypeScript, you can give getters and setters different access modifiers. This creates a controlled pattern where a property is publicly readable but privately writable. Think of it like a display case in a museum: everyone can see the artifact, but only museum staff can place or remove items.
This is different from making the entire property readonly, which would prevent even the class itself from modifying the value after initialization. With asymmetric access, the class can still update the value internally while exposing it safely to external code.
Basic Asymmetric Pattern
The most common pattern uses a public getter and a private setter:
class Counter {
private _count = 0;
public get count(): number {
return this._count;
}
private set count(value: number) {
this._count = value;
}
increment(): void {
this.count = this._count + 1; // Class can use private setter
}
}
const counter = new Counter();
console.log(counter.count); // ✓ Public getter works
counter.increment();
console.log(counter.count); // Shows updated value
// counter.count = 10; // ✗ Error: setter is private
Why Use This Pattern?
Asymmetric access lets you:
- Expose computed or validated state publicly without allowing external mutation
- Maintain internal consistency by controlling all writes
- Encapsulate business logic around property changes
class BankAccount {
private _balance = 0;
public get balance(): number {
return this._balance;
}
private set balance(value: number) {
if (value < 0) {
throw new Error("Balance cannot be negative");
}
this._balance = value;
}
deposit(amount: number): void {
this.balance = this._balance + amount; // Validation runs
}
}
External code can read balance, but all modifications go through controlled methods like deposit(), ensuring validation always occurs.
Common Combinations
You can mix access levels strategically:
class TimestampedData {
private _data: string = "";
private _lastModified: Date = new Date();
// Anyone can read
public get data(): string {
return this._data;
}
// Only subclasses can write
protected set data(value: string) {
this._data = value;
this._lastModified = new Date();
}
// Expose read-only timestamp
public get lastModified(): Date {
return this._lastModified;
}
}
Key Takeaway: Asymmetric getter/setter access lets you create controlled mutation patterns where properties are publicly readable but privately writable, giving you fine-grained control over how your class's state can be observed and modified.