Decorators are a feature of TypeScript that are becoming more and more common in many major libraries. This lesson walks you through what decorators are and how to create your own.
I had to set "noImplicitAny" to false in tsconfig.json to get this to compile properly.
I used:
function addAge(age: number) {
return function(person: any) {
Not sure if there's a class
type in typescript. :/
Great video, thanks John!
After some playing around with the syntax, I have found my footing. Calling the new in the decorator to get the name and then calling new again to instantiate the class, felt a bit inefficient.
Came up with the following solution. instantiating the class within the decorator also gives the decorator the knowledge about the class that is being instantiated.
function PersonDecorator(personProps) {
return targetClass => targetClassArgs => ({
targetClassArgs,
...personProps
});
}
@PersonDecorator({ age: 20, name: 'Cleopatra' })
class Person {
constructor(prop) {
this.someOtherProp = prop;
}
}
console.log(new Person('Hello world'));
// {targetClassArgs: "Hello world", age: 20, name: "Cleopatra"}
But why?