0

I am learning TypeScript and Vue.js.

I have come across a Vue theme that starts with @ on many lines.

What does it do exactly? Is this TypeScript, Javascript or Vue thing?

For example, in one of the Vue store module TypeScript files it looks like this (some code removed for brevity):

@Module
export default class BodyModule extends VuexModule implements StoreInfo {
  classes = {};

  @Mutation
  [Mutations.SET_CLASSNAME_BY_POSITION](payload) {
    const { position, className } = payload;
    if (!this.classes[position]) {
      this.classes[position] = [];
    }
    this.classes[position].push(className);
  }

  @Action
  [Actions.ADD_BODY_CLASSNAME](className) {
    document.body.classList.add(className);
  }

}

Many of those lines such as @Module, @Mutation, and @Action start with with the @ symbol.

I have not seen this many times before.

What does it do exactly?

It looks like a comment of sorts to me. If that is the case, why not use // instead?

TinyTiger
  • 1,801
  • 7
  • 47
  • 92
  • 1
    They're called Decorators and are a TypeScript feature. https://www.typescriptlang.org/docs/handbook/decorators.html – nbokmans Oct 04 '21 at 09:24
  • They are coming to regular javascript as well and is used heavily in frameworks such as Angular, Aurelia, Ember etc. already (though they require a transpiler such as Babel to work). – Karl-Johan Sjögren Oct 04 '21 at 09:30
  • 1
    They are indeed Decorators and do more than commenting. These are actual functions that take on repetitive tasks based on which decorator. You could also write your own decorator. By using decorators like that, Vuex knows that the function is a Mutation and will do extra stuff behind the scenes. – Niels Vanhorenbeeck Oct 04 '21 at 12:50

0 Answers0