What is the most efficient way to simultaneously check multiple variables for undefined values?

Before executing my code, I need to ensure that none of the variables in a given list are undefined.

In the code snippet below, there are 4 variables with uncertain values. While I can manually check variables a and b to satisfy TypeScript's requirements for number types, it becomes tedious when dealing with multiple variables.

Therefore, I attempted to create a function that could simultaneously verify the status of several variables at once. Unfortunately, this implementation resulted in a loss of type information, causing TypeScript to flag the code.

The script is executed with strictNullChecks enabled.

let a = func1(),
    b = func1(),
    c = func1(),
    d = func1();

function func1() {
  return Math.random() === 0 ? 1 : undefined; 
}

function func2(a: number, b: number) {
  console.log(a);
  console.log(b);
}

function anyUndef(a: any[]): boolean {
  return a.filter(e => typeof e === 'undefined').length > 0;
}

if (typeof a !== 'undefined' && typeof b !== 'undefined') {
  func2(a, b);
}

if (!anyUndef([c, d])) {
  func2(c, d);
}

Answer №1

The issue arises when flow control checking does not take into consideration checks performed within functions that are called. A potential solution is to utilize a type guard, but type guards can only assert the type of a single parameter. To address this limitation, tuple types can be employed:

function allDef<T, T2, T3, T4>(a: [T | undefined, T2 | undefined, T3 | undefined, T4 | undefined]): a is [T, T2, T3, T4] 
function allDef<T, T2, T3>(a: [T | undefined, T2 | undefined, T3 | undefined]): a is [T, T2, T3] 
function allDef<T, T2>(a: [T | undefined, T2 | undefined]): a is [T, T2] 
function allDef<T>(a: [T | undefined]): a is [T] 
function allDef(a: any[]): boolean{
    return a.filter(e => typeof e === 'undefined').length > 0;
}
// Helper functions for inferring tuple types
function tuple<T, T2, T3, T4>(a: [T, T2, T3, T4]): typeof a 
function tuple<T, T2, T3>(a: [T, T2, T3]): typeof a 
function tuple<T, T2>(a: [T, T2]): typeof a 
function tuple<T>(a: [T]): typeof a 
function tuple(a: any): typeof a{
    return a;
}

var x = tuple([c, d]); // generate the tuple
if (allDef(x)) { // apply the type assertion
    [c, d] = x; // assign the values back to the variables, ensuring they are not undefined
    func2(c, d);
}

It is uncertain if this approach is superior to manual checking, but it proves effective especially when dealing with multiple variables.

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

Having trouble retrieving an Enum within an Angular template?

I am trying to use an enum to read a property of an array. However, I encountered an error with the following code: <ng-container *ngFor="let elem of list"> <div class="ui-g-12 ui-sm-12 ui-md-12 ui-lg-12 ui-xl-12"> &l ...

Inheritance-based type inference

I have created a class hierarchy to manage inheritance in my code. Here is an example of how it looks: class A { clone(): A { return new A() } methodA() { return this.clone() } } class B extends A { clone(): B{ return new B() } ...

How can you line up various form elements, like pickers, in a row using Material UI?

As someone new to material ui, I haven't come across a solution for my specific issue yet. While there are similar questions, none seem to address the problem of aligning different form field types. My observation is that the material ui date picker ...

Obtain a value that is not defined

Good day, I am encountering an issue with my data not accepting an undefined value. Below is the code snippet: interface IModalContatos { dados: IContatos; onSave(dados: IContatos): void; onClose(): void; } When passing this data to my modal, I rece ...

I'm experiencing difficulties in establishing a connection from Ionic to my remote database

I set up a database on Fauxten and now I'm trying to connect it to my project. Although I can open the link in my browser, nothing happens when I try to call it in the app. I can't figure out what I'm missing. import { Injectable } from &ap ...

Implementing typing for a module that exports an instance of a particular class

Attempting to create a .d.ts file for the foo-foo-mq module has presented some challenges. Following the documentation, a 'foo-foo-mq' folder was created within the 'typings' directory at the project's root. An index.d.ts file was ...

Can we verify the availability of an Angular library during runtime?

I am in the process of creating a custom Angular library, let's name it libA, which has the capability to utilize another Angular library, named libB, for an optional feature. Essentially, if the Angular application does not include libB, then the fea ...

I'm unsure how to utilize the generic type in this particular scenario. It's a bit confusing to me

Recently, I delved into TypeScript generics and applied them in specific scenarios. However, I encountered some challenges. While working with two different interfaces, I faced a need for flexibility. For instance, I needed to make server requests. func ...

TypeScript functions with Generic Constraints return specific values rather than just types

function createGenericCoordinates<Type extends number | string>( x: Type, y: Type ) { return { x, y }; } const genericCoordinates = createGenericCoordinates(1, 2); // Error (TS2322) // Type 3 is not assignable to type 1 | 2 genericCoordinates ...

What is the reason behind Typescript executing the abstract class before anything else?

I'm currently facing a challenge solving an abstract class problem with Typescript. Let me explain what I am trying to accomplish. There is a class named Sword that extends Weapon. Each Weapon must have certain properties like the damage, but since e ...

How can I set a document ID as a variable in Firebase Firestore?

I recently set up a firestore collection and successfully added data (documents) to it. Firestore conveniently generates unique document ids for each entry. Inserting Data this.afs.collection('questions').add({ 'question': message, &a ...

An error persists in PhpStorm inspection regarding the absence of AppComponent declaration in an Angular module

After creating a new Angular application, I am encountering the issue of getting the error message "X is not declared in any Angular module" on every component, including the automatically generated AppComponent. Despite having the latest version of the An ...

What is the method to remove curly brackets from a different data category?

If I have a type like this type Z = {a: number} | {} | {b: boolean} | {c: string} | ...; Is there a way to get the same type but without {}? type Y = Exclude<Z, {}>; ⇧This will result in Y = never, because all variants can be assigned to {} and a ...

Extract data from an HTTP request and assign it to variables using filter and map in Angular

I need to extract data from an http get request and assign it to 3 separate variables once fetched. Data: [ { reportId: 1, results1: [{ name: "TotalReferralsMade", optionId: 3082, factor: 1, description: null ...

Struggling to Decode Octet-stream Data in Angular 6 HttpClient: Encountering Parsing Failure with Error Prompt: "Failed to parse HTTP response for..."

Is there a way to make a non-JSON request to the server using Angular 6 HttpClient (@angular/common/http) in order to receive an Octet-stream? Below is the code I have tried: getFile(file: any) { let headers = new HttpHeaders({ 'Content-T ...

Passing a custom data type from a parent component to a child component in React

I'm currently working on developing a unique abstract table component that utilizes the MatTable component. This abstract table will serve as a child element, and my goal is to pass a custom interface (which functions like a type) from the parent to t ...

Angular 2 rc1 does not support ComponentInstruction and CanActivate

In the process of developing my Angular 2 application with Typescript using angular 2 rc.1, I've noticed that the official Angular 2 documentation has not been updated yet. I had references to ComponentInstruction Interface and CanActivate decorator ...

Exploring Angular 2: How to Retrieve the Value of a Radio Button

How can I retrieve the value of the radio button that is clicked in app.component.html from within app.component.ts? app.component.html <div class="container"> <div class="row"> <div class="col-sm-3 well" style="width: 20%"> ...

What is the best way to reload a React/TypeScript page after submitting a POST request?

I am working on a custom plugin for Backstage that interacts with Argo CD via API calls. To retrieve application information, I make a GET request to the following endpoint: https://argocd.acme.com/api/v1/applications/${app-name} If the synchronizati ...

Encountering difficulty in retrieving the outcome of the initial HTTP request while utilizing the switchMap function in RxJS

My goal is to make 2 HTTP requests where the first call creates a record and then based on its result, I want to decide whether or not to execute the second call that updates another data. However, despite being able to handle errors in the catchError bl ...