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);
}

Upvotes: 1

Views: 316

Answers (2)

epascarello
epascarello

Reputation: 207527

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");
}

Upvotes: 1

Godnyl Pula
Godnyl Pula

Reputation: 125

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

Upvotes: 0

Related Questions