0

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;
4
  • Welcome to SO! Please make sure not to add images of codes and error messages, as we are unable to debug these. Edit your message by adding any relevant codes and a minimal reproducible example. Commented Feb 3, 2023 at 9:45
  • Could you please provide a code example of what you do exactly. Commented Feb 3, 2023 at 9:49
  • @node_modules I am sorry for inconvenience. I have edited the question and added the code in it. Commented Feb 3, 2023 at 10:19
  • @JSEvgeny I am sorry for inconvenience. I have edited the question and added the code in it. Commented Feb 3, 2023 at 10:20

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Got it, so in order to change the type (from number to string), I must re-assign the array cause .push() won't work in that case. right?
Yes. The [] does not give arr1 an actual type. If you assign ["hi"], then arr1 will be a string[] going forward. If you assign a [1,2,3], it will be a number[] going forward.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.