hopeless-programmer
hopeless-programmer

Reputation: 990

Preserve variable name while destructuring in JavaScript/TypeScript

Is it possible to use both variable name and destructuring in a single instruction in JavaScript/TypeScript?

Like this:

function stopTheCar(car & { speed } : Car) {
  if (speed > 10) car.stop()
}

The best closest approach I know is to use destructuring in a separate instruction:

function stopTheCar(car : Car) {
  const { speed } = car

  if (speed > 10) car.stop()
}

But this introduce some limitations. In case of arrow functions blocks are necessary, which might be inconvenient. Like this:

cars.forEach(rect => {
  const { left, top } = rect

  return {
    left,
    top,
    intersection : rect.intersect(anotherRect),
  }
})

Instead of this:

cars.forEach(rect & { left, top } => ({
  left,
  top,
  intersection : rect.intersect(anotherRect),
}))

Upvotes: 1

Views: 417

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 371019

There's no good way. The closest you can get, similar to your first code block, is by using another argument (which is not passed) that defaults to the first:

type Car = {
    speed: number;
    stop: () => void;
}
function stopTheCar(car: Car, { speed } = car) {
    if (speed > 10) car.stop()
  }

But I wouldn't recommend that - it'd be very confusing for consumers of the function to see a possible two arguments when you really only want one to be passed.

Destructuring in the first line of the function instead is the better way, even if it takes a bit of boilerplate.

Upvotes: 2

Related Questions