Updating the Decorators Proposal for the Holidays
The Ecma TC39 committee, which standardizes the JavaScript language (officially known as ECMAScript), has been discussing a decorators proposal for several years. Transpilers like TypeScript and Babel implemented the initial version of the decorators proposal, allowing developers and frameworks to start using the proposal before the feature became an official part of the language standard. However, the proposal has seen significant changes through the standardization process. Decorators will soon arrive in JavaScript, and there are many questions to answer.
What are decorators and why should you care?
Decorators are a metaprogramming language feature, which allows modifying declarations like classes. This pattern looks at program source code as data and allows analyzing and transforming of code. For example, decorators may add add logging to the inputs or outputs of methods. Alternatively, a decorator could add some metadata to a class to configure a framework.
@addMetadata('name-for-library')
class MyClass {
constructor(database) {
This.db = database;
}
@logOutput
makeDatabaseCall(param) {
// call database
const results = this.db.call('query');
**return** results; // this value is automatically logged
}
@bound
methodThatRetainsThis(flagVal) {
// Still knows what this is even when passed as a callback
this.flag = flagVal;
}
}
Similar to languages like Java and Dart, the decorators proposal uses an “@” symbol followed by the decorator name. The proposal champions have been working to align with the class fields proposal so that annotations can get used on classes, class methods, class fields, and likely private fields. This should lead to classes that are powerful yet easy to understand. If you want to learn more, check out SitePen’s previous TypeScript Decorators blog post describing the original decorators proposal.
To see what changes are coming to the decorators proposal, check out my full post on the SitePen blog
Responses
See how to respond...
Respond via email
If you'd prefer to message me directly, send an email. If you'd also like your message to be visible on the site I can add it as a comment.
Reply via Email
Respond from another site
Responses are collected from posts on other sites. Have you posted somewhere that links to this page? If so, share the link!