Spread syntax ES6 with statement
Asked Answered
A

2

20

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 : {}}},
Aerial answered 19/7, 2017 at 8:13 Comment(4)
Does it work? If not, do you get errors? If so, what errors? What's the question you're asking?Bugaboo
My first code works , how to use spread es6 operator with ternary operator inside. The error is 'Unexpected token'Aerial
don't you need a spread operator before {disabled ? ...globalStyles.hintDisabled : {}}Schreck
Rest spread is transpiled to Object.assign invocation, which certainly can be written in form with conditional argument applyingYoung
H
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 : {})},
Hominy answered 19/7, 2017 at 8:27 Comment(4)
What if you only want to spread in one case bot not in the other? Lets say string vs array is the check.Smutch
@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?Hominy
you can spread one array into another or you can just add another itemSmutch
@TheFool This question is not about arrays though. Do you use array spread syntax?Hominy
P
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];
Punic answered 7/9, 2021 at 23:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.