19

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
  • 49,224
  • 10
  • 102
  • 153
Palaniichuk Dmytro
  • 2,943
  • 12
  • 36
  • 66

2 Answers2

54

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
  • 630,263
  • 148
  • 957
  • 1,375
  • 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
  • 1
    @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
1

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];
Kyle Pittman
  • 2,858
  • 1
  • 30
  • 38