Home > database >  Convert (number | number[]) to number[]
Convert (number | number[]) to number[]

Time:10-06

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]

CodePudding user response:

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

const v2 = Array.isArray(v1) ? v1 : [v1];

CodePudding user response:

Since accepted answer seems to have slight 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:

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]
  • Related