Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using ES6 spread syntax in template literal

I need to dynamically define classes so have written a code generator in my ES6 code:

function makeClass(className, baseClass = _DefaultBaseClass, ...args) {
  return (
    eval(`
      class ${className} extends ${baseClass} {
        constructor(${...args}) {
          super(${...args})
        }
      }
   `)
  )
}

'_DefaultBaseClass' is an empty class used to simplify the above generator function logic:

class _DefaultBaseClass() {
  constructor() {}
}

Everything works fine with the generator code, except for the spread operator. The spread operator itself works fine in my project outside of the template literal in this example.

I'm using the following webpack Babel presets/plugins: 'react', 'es2015', 'stage-2', 'transform-runtime'.

like image 786
Ethan Avatar asked Mar 07 '17 02:03

Ethan


1 Answers

As mentioned in the comments ... is bound to specific use cases. ${...args} wouldn't even make much sense. What should be the result? E.g. if ${...args} would be equivalent to ${args[0],args[1]}, then it would evaluate to the value of args[1], because here , is a comma operator.

Template literals can contain arbitrary expressions, so you can do the following:

`${args.join(",")}`
like image 189
a better oliver Avatar answered Jan 02 '23 20:01

a better oliver