Home > Software design >  Destructing string array optional parameters in TypeScript?
Destructing string array optional parameters in TypeScript?

Time:02-15

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?

CodePudding user response:

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

CodePudding user response:

Providing your error report will make it easier to discover your real problem.

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

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

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

And, please note that you can't use TypeScript type annotations in JavaScript. Also the type annotations in the question description is actually not legal.

CodePudding user response:

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"]);
  • Related