Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

143
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda