Exploring the concept of TypeScript's Array Union

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;

Answer №1

When you declare an array like this:

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

You are essentially specifying that the array arr1 can be of type string[] or number[]. However, since you are initializing it as an empty array without a specific type, the compiler won't know if arr1 should be treated as a string[] or number[]. It's only when you start adding values to arr1 where the type is explicitly defined that the compiler can accurately check the type during operations such as push.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it necessary to ensure application readiness before proceeding with unit testing exports?

I've been facing a challenge while trying to utilize Jest for unit testing an express API that I've developed. The issue arises when the database needs to be ready before running the test, which doesn't seem to happen seamlessly. In my serve ...

Merge columns in the top row

Is there anyone who can lend a hand? This is the data_frame that I'm currently working with Here's what I'm aiming to achieve Any tips on how to combine just the cells in the first row using R? I attempted it manually in Excel, but with ...

Retrieving HTML array values using jQuery

Presented below is an array of input boxes. <form> 9 <input type="checkbox" name="date[]" value="9"> 10 <input type="checkbox" name="date[]" value="10"> 11 <input type="checkbox" name="date[]" value="11"> </form> The o ...

Establish a prototype attribute

From what I understand, TypeScript does not make a distinction between prototype properties and instance properties. Additionally, there is no built-in detection for Object.defineProperty on the prototype, which is unlike a feature for typechecking JavaScr ...

A guide to choosing elements within a multi-dimensional array

Trying to perform a straightforward operation, but struggling to find an efficient solution using Numpy functions without generating unnecessary copies of the array. Consider the following 3-dimensional array : In [171]: x = np.arange(24).reshape((4, 3, ...

Implementing Limited Results in Redis FT.SEARCH with TypeScript

Snippet of code: client.ft.SEARCH('license-index-json',"@\\$\\" + ".reservedForApplicationName:GSTest",{ LIMIT: { from: 0, to: 1 } }) Error message: An error occurred when trying t ...

angular directive to receive an object

When I have a table and click on a row, the information is supposed to be displayed in a different component using the @input decorator. However, instead of displaying the correct result in my other component, I am getting [object Object]. table.html < ...

Creating nested objects in Javascript involves adding an object inside another object

There are two objects that I have: obj1= { '201609': 52, '201610': 54, '201611': 56, metric: 'promotionsOut', careerLevelGroups: [ { '201609': 52, &a ...

Which is better: PHP array string or var string?

I've been working with strings in PHP to develop my own framework... There's something that has me curious. $var = "hello!"; $arr = array("h","e","l","l","o","!"); Could someone clarify which one ($var or $arr) consumes more memory and why? I ...

Exploring ways to reach a three-dimensional array beyond the loop

My program is written in C and I am currently working on Ubuntu 14.04. Below is an example of one of the loops that I have implemented. for (x=0; x<1024; x++) { for (i=0; i<8; i++) { for (j=0; j<8; j++) { arr[x ...

Setting a character array equal to a pointer to a character

Having some trouble writing a function that prefixes a string with its length. I'm running into an issue where I can't assign a char[] to a char *. Oddly enough, if I include some debugging code before the assignment, it seems to work. char *pre ...

Having trouble selecting a button located within a form due to the element with the specified locator not being visible

I'm facing an issue while trying to select a button within a Frame. Despite my efforts, I am unable to make the selection. Below is the code snippet that I used to switch to the frame and click on the element in Protractor using TypeScript: await brow ...

The JSON creation response is not meeting the expected criteria

Hello, I'm currently working on generating JSON data and need assistance with the following code snippet: generateArray(array) { var map = {}; for(var i = 0; i < array.length; i++){ var obj = array[i]; var items = obj.items; ...

Troublesome situation encountered when trying to implement React Native/Xcode Release using Typescript

Currently facing an issue while trying to generate a release version of my RN/Typescript project for iOS. I have made some changes to the "Bundle React Native code and images" as follows: export NODE_BINARY=node ../node_modules/react-native/scripts/re ...

The Vue data retrieved from an API using onMounted() is not initially showing up in the DOM. However, it magically appears after I make changes to the template

Hello and thank you to those taking the time to read this. I am new to Vue, so I may be overlooking something obvious here, but after being stuck for several days, I am reaching out for help. In my SFC file, I have an onMounted function fetching data from ...

Assigning a custom class to the cdk-overlay-pane within a mat-select component is restricted to Angular Material version 10.2.7

I attempted the code below, but it only works for angular material 11. My requirement is to use only angular material 10. providers: [ { provide: MAT_SELECT_CONFIG, useValue: { overlayPanelClass: 'customClass' } } ] There a ...

Mapping arrays from objects using Next.js and Typescript

I am trying to create a mapping for the object below using { ...product.images[0] }, { ...product.type[0] }, and { ...product.productPackages[0] } in my code snippet. This is the object I need to map: export const customImage = [ { status: false, ...

Error encountered during Angular unit testing: Unable to read the 'id' property of a null value. (Jasmine, Karma)

I am currently working on writing unit tests for a specific component in my Angular application. The component uses a currentUser variable both in the component logic and the HTML template. I have hardcoded this variable by mocking it in every test using c ...

Version 5 of angularfie2 is encountering an issue where the type 'Observable<{}[]>' cannot be assigned to the type 'Observable<any[]>'

Encountering an error while using angularfire2 version 5: The error reads: "Type 'Observable<{}[]>' is not assignable to type Observable < any [] >." Code snippet: exercisesList$: Observable <any[]>; ionViewDidLoad() { ...

Aggregating various database entries into an array

I want to retrieve data from a MySQL database and store it in an array for comparison. My objective is to compare one variable ($row[0]) with another predefined variable, and based on the result, use the second variable ($row[1]) to perform a new query on ...