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

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

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 Denunciar

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 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