0

I am trying to create constants in javascript. I found this answer helpful. Following that, I wrote something like this.

const ERR1 = 'Error 1',
  ERR2 = 'Error 2',
  ERR3 = 'Error 3',
  ERR4 = 'Error 4'

class Error {
  static get ERR1 () {
    return ERR1
  }

  static get ERR2 () {
    return ERR2
  }

  static get ERR3 () {
    return ERR3
  }

  static get ERR4 () {
    return ERR4
  }
}

Although this works perfectly, I want to reduce the code as it is quite verbose. Probably to one liners using arrow functions like this in class.

static get ERR1 = () => ERR1
static get ERR2 = () => ERR2
...

But, this gives error stating that Unexpected token =. Tried the same with static get ERR1: () => ERR1 and same error Unexpected token :

To answer this question any one of this is sufficient.

  • Why is this an error?
  • Is it possible to write class get using arrow syntax?
  • Is there any shorter way of defining constants?
Jeevan MB
  • 148
  • 1
  • 11
  • The very answer you linked shows many ways to put constants on a `class`, including the use of the experimental class fields proposal syntax which beats everything in conciseness. And yes, you cannot use arrow functions with `get` syntax. – Bergi Sep 12 '18 at 18:38

1 Answers1

1

Javascript syntax bans getters from being arrow functions (see https://stackoverflow.com/a/33827643/1358308 for more info)

I'd probably just do something like:

const Error = Object.freeze({
  ERR1: 'Error 1',
  ERR2: 'Error 2',
  ERR3: 'Error 3',
  ERR4: 'Error 4',
})
Sam Mason
  • 15,216
  • 1
  • 41
  • 60
  • I actually want it to be as a class. There is also a constructor in Error, and some other methods as well. – Jeevan MB Sep 12 '18 at 16:07