🐈 Daniel Rosenwasser Announced TypeScript 5.0 Beta
--
TypeScript 5.0 Beta finally makes decorators a standard feature!
Daniel Rosenwasser just announced TypeScript 5.0 beta. I will walk you through the most important features added in this version. Let’s start:
Decorators
Decorators in EcmaScript were proposed four years ago, and while some transpilers offered them, they didn’t land so far in the EcmaScript standard. They are now on stage 3 meaning it is a draft waiting for the final feedback. When reaching stage 4 decorators will wait for the next release to be made, and become a standard.
Decorators were offered by the TypeScript as an experimental feature that you were able to enable with “experimentalDecorators”: true. Now, they land in the official TypeScript beta, meaning you won’t have to enable them, so they may get some more traction.
Here is the example from the announcement:
@loggedMethod
greet() {
console.log(`Hello, my name is ${this.name}.`);
}
And here is the decorator:
function loggedMethod(originalMethod: any,
context: ClassMethodDecoratorContext) {
const methodName = String(context.name);
function replacementMethod(
this: any,
...args: any[]) {
console.log(`LOG: Entering method '${methodName}'.`)
const result = originalMethod.call(this, ...args);
console.log(`LOG: Exiting method '${methodName}'.`)
return result;
}
return replacementMethod;
}
As you can see, you can apply a decorator with putting the name of the decorator above a function prepended with a @ sign: @loggedMethod.
To actually declare a decorator you write a function with that name that returns a function that will be called every time you will call greet() method.
The nice thing about decorators is that you can put them on everything, so they are reusable. Moreover, you can read information about the context from the context field. For example the method name as in the example above. You can also modify how the decorated function is called.