Home > front end >  modify variable from previous object spread
modify variable from previous object spread

Time:02-23

Say we have this:

interface Seed {
   val: number
}

and we can accept an argument:

const incrementSeedVal = (v: Seed) : Seed => {
  return {...v, ...{val: v.val   1}}
}

I am looking for a way to make this even more concise. Maybe I am imagining things, but isn't there even better shorthand for this operation?

CodePudding user response:

Two Three alternatives:

const incrementSeedVal = (v: Seed): Seed => {
  return {
    ...v,
    val: v.val   1
  }
}

or

const incrementSeedVal = ({ val, ...rest }: Seed): Seed => {
  return {
    ...rest,
    val: val   1
  }
}

or

const incrementSeedVal = ({ val, ...rest }: Seed): Seed => ({
  ...rest,
  val: val   1
})

FWIW: declaring functions without using the function keyword is foolhardy. (This is my own advice and I don't expect other SOers to agree.) All it does is shut off function hoisting, which means you suddenly have to care about the order in which these tools are declared. There is zero value in taking a situation in which there are no wrong answers and converting it to a situation in which there are wrong answers. Make it as easy as possible to succeed and as hard as possible to fail. Use function to declare functions whenever you can. Nobody cares about "coolness points."

  • Related