An accessor method controls property access through getter and setter syntax. Reading invokes a getter; assigning invokes a setter, while the class can keep stored data in a private backing field. section 3.5.3 section 11.3.5
Use accessors when the apparent property needs behavior behind its simple syntax:
- Store the value privately and expose it through a getter and setter. section 11.3.5
- Add logic while keeping callers unaware of the stored representation, such as converting a city into a country. section 11.3.5
- Omit the setter to expose a read-only property. section 11.3.5
- Use a backing-free getter when the returned value is composed from other properties. section 11.3.5
Employee location
A TypeScript Employee stores city privately, exposes location as a property, and translates Paris to France or London to UK in the getter. A setter can update the city; removing it makes location read-only. section 11.3.5
Listing 11.12 Adding accessors in the index.ts file in the src folder
type Person = {
id: string,
name: string,
city: string
};
class Employee {
private city: string;
constructor(public readonly id: string, public name: string,
private dept: string, city: string) {
this.city = city;
}
writeDept() {
console.log(`${this.name} works in ${this.dept}`);
}
get location() {
return this.city;
}
set location(newCity) {
this.city = newCity;
}
}
let salesEmployee = new Employee("fvega", "Fidel Vega", "Sales", "Paris");
salesEmployee.writeDept();
console.log(`Location: ${salesEmployee.location}`);
salesEmployee.location = "London";
console.log(`Location: ${salesEmployee.location}`);
Inspect the complete TypeScript class showing private storage, property-style reads, assignment through a setter, and the resulting output. section 11.3.5












