Midhun Raj
Midhun Raj

Reputation: 987

Difficulty in understanding decorator output using typescript

I am having hard time understanding this code:

function Console(target) {
  console.log('Our decorated class', target);
}

@Console
class ExampleClass {
  constructor() {
    console.log('Yo!');
  }
}

I got output as Our decorated class [Function: ExampleClass] after compiling and running using node why is it that i didnt get Yo!.Can you explain to me this code, I saved it as

decorators.ts

compiled using tsc --target ES5 --experimentalDecorators decorators.ts and then ran node decorators.js

documentation is too tough to understand

I am totally confused in angular we dont need to instantiate a class and everything works fine but here we have to.can you please tell me why we dont need to instantiate a class in typescript

Upvotes: 0

Views: 76

Answers (1)

Alex Wayne
Alex Wayne

Reputation: 187004

console.log('Yo!') is in the constructor of ExampleClass. But you have not actually constructed any instances of ExampleClass. You have only decorated the class object itself.

There is nothing special about a class decorator that would run the constructor of the class it decorates unless you specifically run code that instantiates it.


If you add new ExampleClass() to the end of your code, you will get the "Yo!" that you expect.

Upvotes: 1

Related Questions