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

209
Views
Convert (number | number[]) to number[]

It might be simple question, but I have not figured out as I am still newbie in TypeScript, I have a variable:

let v1: number | number[];

I want to convert

let v2: number[];

If v1 = 1 => v2 will be [1]

if v1= [1, 2] => v2 will be [1,2]

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

0

Test if the variable is an array, create one if not:

const v2 = Array.isArray(v1) ? v1 : [v1];
about 4 years ago · Juan Pablo Isaza Report

0

Slightly more compact method (fully immutable)

Accepted answer seems to have minor side effect (when v1 is array, v2 will inherit reference to v1):

const v1: number | number[] = [1, 2]
const v2: number[] = Array.isArray(v1) ? v1 : [v1] // v1: [1, 2], v2: [1, 2]

v1.push(3) // v1: [1, 2, 3], v2: [1, 2, 3]

I may suggest my solution (simply use Array.prototype.concat()):

let v1: number | number[]
let v2: number[]

v1 = 1

v2 = Array().concat(v1) // v2: [1]

v1 = [1, 2]

v2 = Array().concat(v1) // v2: [1, 2]
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!