TypeScript - Understanding Decorators

InstructorJohn Lindquist

Share this video with your friends

Send Tweet

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.

vtechmonkey
~ 7 years ago

I had to set "noImplicitAny" to false in tsconfig.json to get this to compile properly.

Sports Whispers
~ 7 years ago

I used:

function addAge(age: number) {
    return function(person: any) {

Not sure if there's a class type in typescript. :/

Oscar
~ 6 years ago

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"}
Ivan
~ 6 years ago

But why?