Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

146
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda