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

143
Visualizações
How to write JavaScript constructors without strong typing

In strongly typed languages, like C# or Java, I can distinguish constructor signatures by argument types.

class Cars {

    Cars(string x, string y) {};
    Cars(string x, int y) {};

}

But without strong typing in JavaScript, I can only do this, which obviously will not work:

class Cars {

    Cars(x, y) {};
    Cars(x, y) {};

}

Am I limited to only the number of constructor arguments to distinguish them? Is there some way to create JS constructors that have the same number of args, but of different "types"?

How do I make constructors that know that it should be looking for an string y in the first constructor, but int y in the second?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

The only way to do this with JavaScript itself would be to use typeof checks inside the constructor body.

class Cars {
  constructor(x, y) {
    if (typeof x === 'string' && typeof y === 'string') {
      // implementation
    } else if (typeof x === 'string' && typeof y === 'number') {
      // implementation
    }
  }
}

If you were to use TypeScript, you could make the signatures more explicit and understood by good IDEs (for autocompletion and such) - but you'd still have to write out the tests to differentiate between different parameters inside the constructor itself for the emitted code. Not much of an improvement.

In JS and TS, there is only one constructor for a class - you can't have multiple depending on the types of arguments, you can only modify the one constructor to suit your purposes.

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