Different varieties of typescript variables

My variable is declared with two possible types. Consider this example:

let foo: number | number[] = null;

Then, I have an if condition that assigns either a single number or an array to that variable:

if(condition) { 
  foo = 3;
} else {
  foo = [1,2,3];
}

The issue arises when trying to perform actions on the variable while checking if it is an array.

if(!!foo.length) { ... }

This results in an error message:

Property 'length' does not exist on type number | number[].

I've read about user-defined type guards here: https://www.typescriptlang.org/docs/handbook/advanced-types.html#user-defined-type-guards, but I couldn't get it to work. I also searched on SO without finding a solution.

To somewhat solve this, I resorted to hard-casting using as any, although it's not the most elegant solution.

if(!!(foo as number[]).length) { 
  // This works if foo is an array
} else {
  // This also works, allowing me to assign const a:number = foo;
}

Answer â„–1

To start, the initial type declaration will look like this:

let bar: null | string | string[] = null;

// OR 

bar: string | string[];

Next, employing a type guard is necessary to narrow down the possible types in order to access the variable, for example:

if(typeof bar === 'string') { 
  bar = "Hello";
}
else if (typeof bar === 'object' && Array.isArray(var)) {
  bar = ["apple","banana","cherry"];
}
else {
// do something else
}

Answer â„–2

To determine if a value is an array, you can use the Array.isArray(foo) method:

    if (Array.isArray(foo)){ 
     // Perform logic for arrays
    } else {
      // Perform logic for numbers
}

Answer â„–3

The correction needed is to change lenght to length

Answer â„–4

First, verify if the data is in array format and once you confirm that it is indeed an array, then proceed to review its length:

if(Array.isArray(data) && data.length > 0) { 
    ... 
}

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

Issue with ambient contexts error in TypeScript constructor

What is the correct way to create a constructor in TypeScript? I have been researching and trying different approaches, but it seems like the syntax has changed. Here is my latest attempt: car.d.ts declare class Car { constructor(public engine: string ...

What's the best way to provide route access to the same menu for two distinct user roles using AuthGuard within Angular?

I developed an application that includes three different user roles: ROLE_USER, ROLE_MODERATOR, and ROLE_ADMIN as shown below: export enum Role { User = 'ROLE_USER', Moderator = 'ROLE_MODERATOR', Admin = 'ROLE_ADMIN&apo ...

Can the color of text be adjusted (to either white or black) based on the background color (in any color and format)?

To achieve a text color that contrasts well with any background, I need to make sure it's either black or white. The background in my app can vary in color and format, so finding the perfect solution has been challenging. Using mix-blend-mode doesn&a ...

Issue: Transition of FCM to HTTP v1 API from Previous Legacy API

Recently, I have been working on migrating FCM from the legacy API to the HTTP V1 API. Here's a comparison of the "working code before" and after the necessary modifications: Before: const payload = { data: ...

When examining two arrays for similarities

I am dealing with two arrays within my component arr1 = ["one", "two"] arr2 = ["one", "two"] Within my HTML, I am utilizing ngIf in the following manner *ngIf="!isEnabled && arr1 != arr2" The isEnabled condition functions as expected, however ...

What is the most effective method for comparing two arrays of objects and extracting the differing values within a React application?

I am currently working on implementing a changelog feature for my website. Let's consider the initial array as initArray: [ { "id": 1, "val1": "2023-08-28", "val2": 1, " ...

How can we avoid excessive re-rendering of a child component in React when making changes to the parent's state?

In my React application, I am facing a situation where a parent component controls a state variable and sends it to a child component. The child component utilizes this state in its useEffect hook and at times modifies the parent's state. As a result, ...

Changing the positions of objects on a resized HTML Canvas

I am currently developing a tool that allows users to draw bounding boxes on images using the Canvas and Angular. Everything was working smoothly until I encountered an issue with zooming in on the canvas causing complications when trying to draw bounding ...

Issue arises when TypeScript attempts to verify the presence of an array element

I am facing an issue with the following array declaration: // Using const as I require it to be a specific type elsewhere const fruits = ["strawberry", "banana", "orange", "grapefruit"] as const; When attempting to ...

Include a string in every tuple

I am trying to define a new type: type myNewType = 'value-1' | 'value-2' | 'value-3' Is there a way to create another type like this? type myNewType2 = '1' | '2' | '3' However, I want the outpu ...

Optimizing row performance for Angular grids in the Chrome browser

When creating a component that includes a table with numerous rows, everything works well with small amounts of data. However, once the item count reaches 2000 or more, it starts lagging. Scrolling and animations become sluggish. Even after trying to impl ...

What could be causing the "Failed to compile" error to occur following the execution of npm

Exploring react with typescript, I created this simple and basic component. import React, { useEffect, useState } from "react"; import "./App.css"; type AuthUser = { name: string; email: string; }; function App() { const [user, setUser] = useState& ...

A single click is required for Observables to load on an HTML page

While working on my Angular web application, I encountered an issue with displaying data when using Observables and Subjects. Typically, when searching the Firebase DB, I use *ngFor="let myvar of _myvar | async" in my HTML to display the retrieve ...

Whenever the route changes in Angular, the components are duplicated

Whenever I switch routes in my Angular application, such as going from home to settings and back to home, all the variables seem to be duplicated from the home page and are never destroyed. I noticed that I created a loop in the home component that displa ...

What is preventing you from utilizing TypeScript's abstract classes for generating React factories, especially when regular classes seem to function properly?

Here is an example showcasing the behavior of TypeScript code using React with abstract classes: import * as React from "react"; class MyComponent<P> extends React.Component<P, any> { static getFactory() { return React.createFacto ...

Using TypeScript and the `this` keyword in SharePoint Framework with Vue

I'm currently developing a SharePoint Framework web part with Vue.js. Check out this code snippet: export default class MyWorkspaceTestWebPart extends BaseClientSideWebPart<IMyWorkspaceTestWebPartProps> { public uol_app; public render(): ...

Having trouble with Ionic 3's Screen Orientation Lock feature not functioning properly?

I am in need of a solution that will lock my app to portrait mode on phones and landscape mode on tablets, beginning with the splashscreen. I attempted to use the Screen Orientation plugin from Ionic Native, but unfortunately, it did not work for me. Here ...

Ways to showcase product information (Using Angular and Firebase)

Information product.model.ts id?: string; name: string; price: number; sale_price: number; description: string; tech_sheet: string; imageUrls: string[]; category: string; createdAt: Date; } Initialize file product.service.ts The latest f ...

The package information could not be loaded from the registry due to an error: The "timeout" parameter must be in numerical form. Instead, it was received as a string ('100000')

Encountered an issue while trying to install Angular Material in my project: PS C:\Users\Avinash Kumar\Desktop\Projects\CRUD\Project 2\Library Management System\UI\UI\Frontend> ng add @angular/material â ...

Guide to customizing default selections in Plotly modeBar

I am currently developing an Angular 6 application that utilizes Plotly.js to create a scatter plot. One of the requirements I have is to set the default modeBar selection to "Show closest data on hover" (hoverClosestCartesian as mentioned in the document ...