Home > Software engineering >  TypeScript Array Union
TypeScript Array Union

Time:02-04

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;

CodePudding user response:

Here ...

   let arr1: string[] | number[] = [];

... you are basically saying: There is an array arr1 which can either be of type string[] or number[]. At the same time you are assigning an array without any type, so the compiler will not actually know if arr1 is a of type string[] or number[]. As soon as you assign values to the arr1 where the compiler knows the type, it can also correctly check the type when invoking the push operation.

  • Related