Controlled assignment
Normalize or validate values before storing them.
TypeScript · Const
TypeScript accessors use get and set methods to control property reads and writes while preserving property-like syntax. A getter-only accessor is inferred as readonly.
Accessor pairs intercept reads and writes to a class member. A getter supplies the value returned by a read, while a setter receives assigned values and can validate, normalize, or otherwise control the update.
class Type {
get property(): ValueType { ... }
set property(value: ValueType) { ... }
}A getter returns the value read from the member; a setter handles assignment and does not return a member value.
get and set declarations to intercept reads and writes to an object member.class Person {
private _name: string;
constructor(name: string) {
this._name = name;
}
get name(): string {
return this._name;
}
set name(value: string) {
this._name = value.trim();
}
}
const person = new Person("Ada");
person.name = " Grace ";
console.log(person.name);The getter controls reads and the setter validates or transforms writes to the same property.
Normalize or validate values before storing them.
Expose computed data through property syntax.
Keep implementation storage private while exposing a stable member API.
A getter runs when code reads a member, and a setter runs when code assigns to it. This lets a class control access rather than exposing storage directly.
Follow-up: What happens if only a getter exists? The property is inferred as readonly.
The compiler must emit ECMAScript 5 or newer for accessors. ECMAScript 3 output is unsupported.
Follow-up: How can a getter-only property communicate its write restriction in generated declarations? It is represented as readonly.
A getter without a corresponding setter is automatically inferred as readonly. This also makes the restriction visible to consumers of generated declaration files.
Follow-up: Can a class still update the underlying value internally? Yes, provided the implementation has appropriate private storage or another internal mechanism.
getsetreadonlyClasses