1. Introduction
Getters and setters (accessors) let a class expose what looks like a normal property from the outside, while actually running a method behind the scenes. This makes it possible to compute derived values on read, or validate and transform values on write, without changing how callers interact with the property.
Cricket analogy: A Player class's strikeRate getter computes runs divided by balls faced on the fly whenever player.strikeRate is read, looking like a plain property to the caller even though a calculation runs behind the scenes.
2. Syntax
class ClassName {
private _value: Type;
get propertyName(): Type {
return this._value;
}
set propertyName(newValue: Type) {
this._value = newValue;
}
}
const instance = new ClassName();
instance.propertyName; // calls the getter
instance.propertyName = val; // calls the setter3. Explanation
A get accessor runs whenever the property is read, and a set accessor runs whenever the property is assigned a new value, but callers use ordinary property syntax (instance.propertyName), not method-call syntax. This is commonly paired with a private backing field (often prefixed with an underscore) that stores the real value, while the public getter/setter pair controls access to it.
Cricket analogy: Setting player.jerseyNumber = 18 runs a set jerseyNumber(value) accessor behind the scenes, storing it in a private _jerseyNumber field, while the caller writes ordinary property syntax rather than calling a method like setJerseyNumber(18).
Setters are a natural place to add validation logic — for example, rejecting an invalid value by throwing an error before it's ever stored. A class can also define a getter with no matching setter, in which case the property becomes effectively read-only from the outside, even though it isn't declared with the readonly keyword.
Cricket analogy: A set battingAverage(value) accessor can throw an error before storing a negative average, and a Player class that only defines get careerRuns() with no matching setter makes that stat effectively read-only, even without the readonly keyword.
If a class defines only a get accessor for a property with no matching set accessor, that property becomes effectively readonly from outside the class — any attempt to assign to it (e.g. instance.fahrenheit = 100) is a compile-time error, even though the readonly keyword was never used.
4. Example
class Temperature {
private _celsius: number;
constructor(celsius: number) {
this._celsius = celsius;
}
get celsius(): number {
return this._celsius;
}
set celsius(value: number) {
if (value < -273.15) {
throw new Error("Temperature below absolute zero");
}
this._celsius = value;
}
get fahrenheit(): number {
return (this._celsius * 9) / 5 + 32;
}
}
const t = new Temperature(25);
console.log(t.celsius);
console.log(t.fahrenheit);
t.celsius = 30;
console.log(t.celsius);
console.log(t.fahrenheit);5. Output
25
77
30
866. Key Takeaways
- get and set accessors let a property run custom logic while still being accessed with plain property syntax.
- Setters are a natural place for validation before storing a value in a private backing field.
- A getter with no matching setter makes a property effectively readonly from outside the class.
- Getters can compute derived values on the fly, like fahrenheit derived from _celsius.
- Backing fields (e.g. _celsius) are conventionally private and prefixed with an underscore.
Practice what you learned
1. What happens if a class defines a get accessor for 'fahrenheit' but no matching set accessor?
2. In the Temperature example, what is printed by console.log(t.celsius) immediately after `const t = new Temperature(25);`?
3. After `t.celsius = 30;`, what does console.log(t.fahrenheit) print?
4. Why is a setter a good place to put validation logic, as shown with the 'Temperature below absolute zero' check?
5. From the caller's perspective, how is a getter/setter accessed compared to a regular method?
Was this page helpful?
You May Also Like
Classes in TypeScript
Learn how TypeScript classes add type-checked properties, methods, and constructor parameter property shorthand on top of ES2015 classes.
Access Modifiers in TypeScript (public, private, protected)
Control the visibility of class members with public, private, and protected, and understand that these checks exist only at compile time.
Readonly Properties in TypeScript
Use the readonly modifier to prevent a class property from being reassigned after it is initially set in the constructor or at declaration.
Static Members in TypeScript
Define properties and methods that belong to the class itself rather than to individual instances, using the static keyword.
Related Reading
Related Study Notes in Programming
Browse all study notesApache Spark Study Notes
Programming · 30 topics
ProgrammingApache Flink Study Notes
Programming · 30 topics
ProgrammingHadoop Study Notes
Programming · 30 topics
ProgrammingSnowflake Study Notes
Programming · 30 topics
ProgrammingApache Airflow Study Notes
Programming · 30 topics
Programmingdbt (Data Build Tool) Study Notes
Programming · 30 topics