I've been exploring Typescript union and encountered an issue when assigning an array with the type number[] | string[]. Whenever I try to push a string or number into it, I receive the error message "Argument of type 'string' is not assignable to parameter of type 'never'".
let arr1: string[] | number[] = [];
let arr2: (string | number)[] = [];
let arr3: Array<number | string> = [];
arr1.push(21);
//Error occurs with the above push
arr2.push(1);
arr2.push("John Wick");
arr3.push(2);
arr3.push("John Wick");
My intention is to have arr1 as either a number array or a string array.
Could someone please shed light on what's happening here?
Is this issue related to unions? Because there are no problems when assigning a new array, only when using .push().
let arr1: string[] | number[] = [];
let arr2: (string | number)[] = [];
let arr3: Array<number | string> = [];
arr1 = ["John", "Wick"];
arr1 = [0, 1, 2];
//No errors in these assignments
let variable: string | number = "true";
variable = 21;