1

I need to implement a string concatenate function, the functionality shows below,

function concatenation(original: string, name1?, name2?){
  return original + name1 + name2;
}

However, the question is, there can be more parameters about name; therefore, this is a not a good coding style. I want to change its like shows below.

function concatenation(original: string, name?:[string]){
  return original + ...name1;
}

But in this way, the program will report an error. How could I achieve it?

3 Answers 3

3

You can use rest with join as:

function concatenation(original: string, name1?, name2?) {
  return original + name1 + name2;
}
concatenation('Original', 'Name1', 'Name2', 'Name3');

This can handle any number of string arguments

function concatenation2(...names: string[]) {
  return names.join('');
}

concatenation2('Original', 'Name1', 'Name2', 'Name3');

function concatenation2(...names) {
  return names.join('');
}

console.log(concatenation2('Original', 'Name1', 'Name2', 'Name3'));

Sign up to request clarification or add additional context in comments.

Comments

2

Providing your error report first will make it easier to discover your real problem. In this case, you should know that type annotations are from TypeScript and can only be used in .ts relevant environment.

In fact, what your function concatenation do is simply concating multiple string variables, though you tried to distinguish them by name. Since you want to place the strings sequentially as arguments of the function, you could simply use destructuring assignment.

function concatenation(...items) {
    // now `items` is an Array consisting of all the arguments provided.
    return items.join('');
}

concatenation(1, 2, 3) // "123"
concatenation("a", "bcd", "ef", "g", "h") // "abcdefgh"

Comments

0

You cannot destructure javascript object with any type of arithmetic operator like ( +, - , etc...).

function concatenation(original: string, names?: [string]) {
  return `${original}${names.split("")}`;
}

concatenation("original", ["name1", "name2", "name3"]);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.