Can't use spread operator with ternary operator

Viewed 595

I'm trying to run a command with spawn from cross-spawn package, to install some dependencies with npm programmatically, these dependencies can be both rollup packages, or webpack packages, depending on the value of the variable bundler

spawn.sync(
  'npm',
  [
    'add',
    '-D',
    'svelte',
    bundler === 'rollup' ? ...rollupPackages : ...webpackPackages
  ],
  { cwd: projectPath }
)

But typescript compiler is complaining, more specifically on the spread operator of rollupPackages with the following message:

Expression expected. ts(1109)

2 Answers

Found the solution, instead of destructuring each variable of the ternary operation, wrapping the entire conditional and destructuring it from the outside worked well, example below:

spawn.sync(
  'npm',
  [
    'add',
    '-D',
    'svelte',
    ...(bundler === 'rollup' ? rollupPackages : webpackPackages)
  ],
  { cwd: projectPath }
)

I assume both package variables are arrays and you want to add the individual array values as own values in the .sync call param array, so try wrapping the entire expression in parentheses:

spawn.sync(
  'npm',
  [
    'add',
    '-D',
    'svelte',
    (bundler === 'rollup' ? ...rollupPackages : ...webpackPackages)
  ],
  { cwd: projectPath }
)
Related