david raj
david raj

Reputation: 153

Are Decorators allowed in NodeJS?

I'm trying to run the following code in NodeJS using terminal

function addStringToName(target, name, descriptor) {
    const fn = descriptor.value;
    descriptor.value = wrestler => {
        fn.call(target, wrestler + ' is a wrestler');
    };
}

class Wrestler {
    @addStringToName
    setName(name) {
        this.name = name;
    }
    sayName() {
        console.log(this.name);
    }
}

const w = new Wrestler();
w.setName('Macho Man');
w.sayName();

Getting the following error

Error

Can Decorators be used in NodeJS if yes what is wrong with the written code ?

Upvotes: 5

Views: 4254

Answers (1)

Yegor
Yegor

Reputation: 1108

Unfortunately, no. You have to use TypeScript in order to have decorators enabled. Moreover, even TypeScript doesn't support it natively. You will have to have target: "ES5" at least and "experimentalDecorators": true.

You can find more about decorators and TypeScript here: https://www.typescriptlang.org/docs/handbook/decorators.html

Upvotes: 3

Related Questions