Property Decorators
A Property Decorator is declared just before a property declaration. A property decorator cannot be used in a declaration file, or in any other ambient context (such as in a declare
class).
The expression for the property decorator will be called as a function at runtime, with the following two arguments:
- Either the constructor function of the class for a static member, or the prototype of the class for an instance member.
- The name of the member.
NOTE A Property Descriptor is not provided as an argument to a property decorator due to how property decorators are initialized in TypeScript. This is because there is currently no mechanism to describe an instance property when defining members of a prototype, and no way to observe or modify the initializer for a property. As such, a property decorator can only be used to observe that a property of a specific name has been declared for a class.
If the property decorator returns a value, it will be used as the Property Descriptor for the member.
NOTE The return value is ignored if your script target is less than
ES5
.
We can use this information to record metadata about the property, as in the following example:
class Greeter { @format("Hello, %s") greeting: string; constructor(message: string) { this.greeting = message; } greet() { let formatString = getFormat(this, "greeting"); return formatString.replace("%s", this.greeting); } }
We can then define the @format
decorator and getFormat
functions using the following function declarations:
import "reflect-metadata"; const formatMetadataKey = Symbol("format"); function format(formatString: string) { return Reflect.metadata(formatMetadataKey, formatString); } function getFormat(target: any, propertyKey: string) { return Reflect.getMetadata(formatMetadataKey, target, propertyKey); }
The @format("Hello, %s")
decorator here is a decorator factory. When @format("Hello, %s")
is called, it adds a metadata entry for the property using the Reflect.metadata
function from the reflect-metadata
library. When getFormat
is called, it reads the metadata value for the format.
NOTE This example requires the
reflect-metadata
library. See Metadata for more information about thereflect-metadata
library.
Please login to continue.