Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

142
Views
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),
}))
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!