I am learning about Typescript union. I assigned an array with type number[] | string[]. But When I am pushing any string or number in it. Then I am getting an error " 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 for above push
arr2.push(1);
arr2.push("John Wick");
arr3.push(2);
arr3.push("John Wick");
Here I want to make arr1 to be either number or string array.
Can someone please help me understand what is happening here.
Is it possible because of union? Cause when I am assigning a new array, then there is no problem. It's only in the case of .push()
let arr1: string[] | number[] = [];
let arr2: (string | number)[] = [];
let arr3: Array<number | string> = [];
arr1 = ["John", "Wick"];
arr1 = [0, 1, 2];
//No Error here
let number: string | number = "true";
number = 21;