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

92
Views
Typescript concat two data types array in one

How do I concat two types array in one array using concat. If I initialize it with two data types it works fine but when I concat it. Typescript throws an error that both types are incompatible.

const foo: string[] = ['hello', 'world'];
const bar: number[] = [1, 2];
const both: (string | number)[] = foo.concat(bar); // gets an error on bar

const other: (string | number)[] = ['hello', 'world', 2, 3]; // this works
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

I think it has to do with the implementation of .concat() in Typescript. It is implemented as the type of the merged array is expected to be the type of foo here. That is the reason it is throwing an error.

You can check the error tab for your code snippet from Typescript Playground here to understand more about this.

If you want to make it work, you can use the spread operator. It should work fine.

const foo: string[] = ['hello', 'world'];
const bar: number[] = [1, 2];
const both: (string | number)[] = [...foo, ...bar]; 
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!