Adjust descriptor flags
Change whether an accessor can be reconfigured after class definition.
TypeScript · Decorator
An accessor decorator runs on a getter or setter’s property descriptor, letting code observe, modify, or replace the accessor definition. It receives the owning constructor or prototype, the member name, and the descriptor.
An accessor decorator is placed immediately before a getter or setter. At runtime, TypeScript calls it with the class constructor or prototype, the member name, and the accessor’s property descriptor, allowing the descriptor to be inspected, changed, or replaced.
function decorator(target: Function | object, name: string | symbol, descriptor: PropertyDescriptor): void | PropertyDescriptor| Name | Type | Description |
|---|---|---|
target | Function | object | The class constructor for a static accessor, or the class prototype for an instance accessor. |
name | string | symbol | The accessor’s property name. |
descriptor | PropertyDescriptor | The property descriptor shared by the accessor member. |
The decorator may return a property descriptor to replace the accessor definition; it may also return nothing.
function configurable(value: boolean) {
return function (target: object, name: string | symbol, descriptor: PropertyDescriptor) {
descriptor.configurable = value;
};
}
class Service {
private _enabled = true;
@configurable(false)
get enabled() {
return this._enabled;
}
}
console.log(new Service().enabled);The decorator receives the instance prototype, accessor name, and shared property descriptor, then changes the descriptor’s configurability.
Change whether an accessor can be reconfigured after class definition.
Wrap or replace getter/setter behavior through the descriptor.
Inspect the owning class and member name while processing class definitions.
An accessor decorator is declared immediately before an accessor and is applied to its property descriptor. It can observe, modify, or replace the accessor definition.
Follow-up: Why is the descriptor shared by a getter and setter? Because the descriptor represents the combined property rather than either accessor declaration independently.
For an instance accessor, the first argument is the class prototype; for a static accessor, it is the constructor. The second argument is the member name, and the third is the property descriptor.
Follow-up: What must a decorator change to affect configurability? It should update the relevant descriptor property before the decorated member is installed.
A member with both get and set accessors must have its decorators placed on only the first accessor in document order. Decorating both is rejected because both declarations use one property descriptor.
Follow-up: How should a pair of accessors be decorated? Put the decorator on the first accessor and treat it as applying to the whole property.
DecoratorProperty Descriptorget accessorset accessor