TypeScript — Accessors: Getters and Setters for Controlled Property Access
Introduction – What Are Accessors in TypeScript?
In TypeScript, accessors are special methods called getters (get) and setters (set) used to read from and write to a class property with additional logic. They offer a way to encapsulate data, enforce validations, log usage, or transform values before returning or assigning them—all while interacting with the property as if it were a simple field.
In this guide, you’ll learn:
- What getters and setters are in TypeScript
- How to define and use accessors in classes
- The benefits of using accessors over public fields
- Real-world use cases and best practices
What Are Getters and Setters?
Accessors provide a mechanism to intercept property access. You can define custom logic to be executed when a property is read or written.
Syntax:
class Example {
private _data: string = "";
get data(): string {
return this._data;
}
set data(value: string) {
this._data = value.trim();
}
}
Usage:
const obj = new Example();
obj.data = " Hello TypeScript ";
console.log(obj.data); // Output: Hello TypeScript
The set trims the value before storing it, and the get returns the clean result.
Why Use Accessors?
- Add validation logic before assigning values
- Format or sanitize data automatically
- Log or monitor property usage
- Enforce read-only or write-only behavior
- Create computed or derived properties
Getter (get) in TypeScript
A getter lets you return a property value, often with computed logic.
Example:
class Rectangle {
constructor(private width: number, private height: number) {}
get area(): number {
return this.width * this.height;
}
}
const rect = new Rectangle(10, 5);
console.log(rect.area); // Output: 50
Even though area is not a field, it behaves like one and returns a computed value.
Setter (set) in TypeScript
A setter lets you control how a property is assigned.
Example:
class Person {
private _age: number = 0;
set age(value: number) {
if (value < 0) {
throw new Error("Age cannot be negative");
}
this._age = value;
}
get age(): number {
return this._age;
}
}
const p = new Person();
p.age = 30; //
console.log(p.age); // 30
// p.age = -5; // Error: Age cannot be negative
Read-Only or Write-Only Properties
You can expose only a getter or setter to create read-only or write-only properties.
class Secret {
private _code: string = "XYZ123";
get code(): string {
return this._code;
}
// No setter — makes the property read-only externally
}
Accessors with Access Modifiers
TypeScript allows you to use public, private, and protected with accessors:
class Document {
private _title = "";
public get title(): string {
return this._title;
}
protected set title(value: string) {
this._title = value;
}
}
You can control read and write scope separately using access modifiers.
Computed Properties with Getters
Getters can return dynamic or derived values:
class Currency {
constructor(private amount: number) {}
get formatted(): string {
return `$${this.amount.toFixed(2)}`;
}
}
const price = new Currency(15.5);
console.log(price.formatted); // $15.50
Common Mistakes & How to Avoid Them
| Mistake | Solution |
|---|---|
| Assigning directly to a getter | Getters can’t accept values — define a set to make it writable |
| Using logic-heavy setters | Keep setters simple and fast — avoid heavy processing |
Forgetting the backing field (_x) | Always use private backing fields to avoid recursive loops |
| Calling getter like a function | Getters are accessed like properties (obj.name, not obj.name()) |
Best Practices for Accessors
- Use
getandsetfor encapsulation and data validation - Name backing fields with a
_prefix (e.g.,_name) to avoid recursion - Keep logic inside accessors lightweight and predictable
- Combine with access modifiers to control scope and protect internal data
- Avoid using accessors for performance-critical hot paths
Summary – Recap & Next Steps
Accessors in TypeScript allow you to add control, validation, and customization to class property access. With get and set, you can write object-oriented code that enforces rules while maintaining clean and intuitive syntax.
Key Takeaways:
getandsetprovide controlled access to private properties- Ideal for validation, formatting, and computed values
- Accessors behave like properties, not methods
- Use backing fields to store actual data
- Protect access with
private,public, orprotected
Real-world relevance: Used in state management, user inputs, model validation, configuration objects, and domain entities.
FAQs – Accessors in TypeScript
Can I define a getter without a setter?
Yes. This creates a read-only property.
Can I access a getter like a method (obj.getName())?
No. Accessors are used like properties: obj.name, not obj.name().
Can I overload accessors in TypeScript?
No. TypeScript does not support accessor overloading.
Is there a performance cost with getters/setters?
Slightly more than direct access—but generally negligible unless overused.
Do accessors exist at runtime?
Yes. Unlike interfaces or types, accessors are compiled to JavaScript methods.
Share Now :
