16

I tried to write ternary operator with spread syntax and copy two objects. Is it possible to use ternary operator with spread syntax inside with literal objects? My code works okay, I just want to optimize it.

hintStyle: disabled ? {...globalStyles.hint, ...globalStyles.hintDisabled} : globalStyles.hint,

I want to write like this:

hintStyle: {...globalStyles.hint, {disabled ? ...globalStyles.hintDisabled : {}}},
Patrick Roberts
  • 44,815
  • 8
  • 87
  • 134
Palaniichuk Dmytro
  • 2,553
  • 7
  • 30
  • 61

2 Answers2

43

Spread is not an operator, it's part of the object literal syntax (or at least it will be when the proposal is accepted). You need to write

{...globalStyles.hint, ...(disabled ? globalStyles.hintDisabled : {})},
Bergi
  • 572,313
  • 128
  • 898
  • 1,281
  • What if you only want to spread in one case bot not in the other? Lets say string vs array is the check. – The Fool Sep 30 '20 at 16:46
  • @TheFool You can only spread an object into an object. If you have a value that is not an object, how do you want to make it part of the object? – Bergi Sep 30 '20 at 20:31
  • you can spread one array into another or you can just add another item – The Fool Sep 30 '20 at 23:43
  • @TheFool This question is not about arrays though. Do *you* use array spread syntax? – Bergi Sep 30 '20 at 23:53
0

I ran into this same problem today, my use case was simple enough that I could do this:

// given any-typed parameters a and b, I want to append b to a
// if a is iterable, I want to use spread.
// Initially I had:

const fn1 = (a, b) => [Symbol.iterator in a ? ...a : a, b]

// This was my solution:

const fn2 = (a, b) => Symbol.iterator in a ? [...a, b] : [a, b];
Monkpit
  • 2,500
  • 1
  • 27
  • 35