Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

227
Views
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?

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report

0

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.

about 4 years ago · Juan Pablo Isaza Report

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"]);
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!