Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Destructing string array optional parameters in TypeScript?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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'));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading