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

100
Visualizações
Can I specify the DataType to be returned on a JavaScript function?

Is there a way to create a function that only returns strings? For context, I was trying to create the function attached as a screenshot, with the aim of concatenating two strings and returning another string. However, the function also worked on numbers, as it added them. In some cases, I would only want the function to work on a particular data type. Is this possible?

screenshot here

function concatenate(a,b) {
  return (a+b);
}
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

So you either convert them the types you want

function example (a, b) {
  return a.toString() + b.toString();
}
console.log(example("foo", "bar"));
console.log(example(1, 2));

Or you do validation on the types

function example (a, b) {
  if (typeof a !== "string" || typeof b !== "string" ) {
    throw new Error("Strings expected");
  }
  return a + b;
}
console.log(example("foo", "bar"));
console.log(example(1, 2));

If you really care about string vs String

if (
  !(typeof a === 'string' || a instanceof String) || 
  !(typeof b === 'string' || b instanceof String)) {
  throw new Error("Strings expected");
}
about 4 years ago · Juan Pablo Isaza Relatório

0

Generic function can be created accepting the type and it can return function making all validations which can be used to perform action.

function GenericConcat(typeA,typeB) {
  return (a,b) => {
    if (typeof a == typeA && typeof b == typeB ) {
      return a + b;
    }
    throw new Error("Parameter type expected: "+ typeA +"-"+ typeB);
  }
}
stringConcate = GenericConcat("string","string");
stringConcate("a","b"); //ab
stringConcate("a",1)    //Error: Parameter type expected: string-string

numberConcate = GenericConcat("number","number");
numberConcate(1,2);     //3 
numberConcate("a",1);   //Error: Parameter type expected: number-number
GenericConcat("string","string")("A","B");
GenericConcat("number","number")(1,2);
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