What is the accessor keyword in TypeScript 4.9?
Answer
TypeScript 4.9 introduced the accessor keyword for class fields, which automatically generates getter and setter methods using the ECMAScript accessor property proposal. Syntax: class Person { accessor name: string = ""; }. This is shorthand for: class Person { private _name: string = ""; get name() { return this._name; } set name(value: string) { this._name = value; } }. The generated getter and setter use a private backing field (implementation details vary). Benefits: cleaner syntax for reactive properties, better integration with decorators (the @accessor decorator can intercept get/set operations), and consistent behavior across class hierarchies. The accessor keyword is particularly useful with the new decorator standard (stage 3) where @accessor decorators can add validation, change notification, or transformation logic to individual properties. It enables patterns like observable properties in UI frameworks without verbose boilerplate.
Previous
What are type-safe event emitters in TypeScript?
Next
How do you create a type-safe builder pattern in TypeScript?
More TypeScript Questions
View all →- Advanced What is structural typing in TypeScript?
- Advanced What are branded types (opaque types) in TypeScript?
- Advanced What is the Variance annotation in TypeScript 4.7?
- Advanced What is the satisfies operator used for in TypeScript?
- Advanced How do you implement a deep partial type in TypeScript?