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

The issue arises when attempting to drop elements from two lists with incorrect positions and mismatched coordinates

Angular 9 had a working version of this, which you can find here: https://stackblitz.com/edit/two-drop-list-problem-zp556d?file=package.json Now in the new Angular 14 version: https://stackblitz.com/edit/angular-ivy-1jvbnn?file=src%2Fapp%2Fapp.component ...

I am looking for a guideline that permits me to restrict the use of a form validation tool

We have developed our own version of the Validators.required form-validator that comes with Angular 7, but now we need to switch to using CustomValidators.required. To enforce this change, we are considering banning the use of the old Validators.required b ...

Learn how to utilize the combineLatest/zip operators to only respond to emissions from the second observable while disregarding emissions from the first observable

Here's an example of how I'm initializing a property: this.currentMapObject$ = zip(this.mapObjects$, this.currentMapObjectsIndex$, (mapObjects, index) => mapObjects[index]); I want the value of this.currentMapObject$ to be emitted only ...

Alerting Users Before Navigating Away from an Angular Page

I am looking to implement a feature in my app that will display a warning message when attempting to close the tab, exit the page, or reload it. However, I am facing an issue where the warning message is displayed but the page still exits before I can resp ...

Steer clear of using the non-null assertion operator while assigning object members

Looking for a practical method to assign object members to another object without using the non-null assertion operator "!". In the example below, consider that formData can be any JavaScript object. some.component.ts export class SomeComponent { someMo ...

Decorators do not allow function calls, yet the call to 'CountdownTimerModule' was executed

While building production files, the aot process is failing with this error message: Function calls are not supported in decorators but 'CountdownTimerModule' was called. I run the build command using npm run build -- --prod --aot and encounter ...

Ways to activate subscriptions in type-graphql?

I'm encountering an issue with setting up subscriptions in my Apollo Server project using Express. Despite following all the steps outlined in the documentation [https://typegraphql.com/docs/subscriptions.html], I can't seem to get it working. In ...

Generate a data type automatically based on an Array

Imagine having an imaginary api that provides color values based on user selections. Consider the following arrays with string values: const Colors1 = ['red', 'blue', 'purple']; const Colors2 = ['blue', 'white& ...

Having trouble with @viewChild not activating the modal popup and displaying an error message stating that triggerModal is not a function in

I am facing an issue where the click event is not being triggered from the parent component to display a Bootstrap 3 modal. I am getting the following error: ERROR TypeError: this.target.triggerModal is not a function This is what I have done so far: Pa ...

Guide to setting a generic key restriction on a function parameter

Today, I decided to have some coding fun and try creating a generic pushUnique function. This function is designed to check if a new object being added to an array is unique based on a key, and then push it if it meets the criteria. At this point, all I h ...

NextJS-created calendar does not begin on the correct day

I'm facing an issue with my calendar code where it starts rendering on a Wednesday instead of a Monday. I want to adjust the layout so that it always begins on a Monday by adding some empty boxes at the start of the calendar. Essentially, I need to s ...

Steps for updating the value of a button in Typescript and React

I currently have a button that manages my language switcher, configured to handle cookies, URL changes, and now I want it to update the translations on the page as well. The <img> tag is utilized for changing the country flag. < ...

Finding the final day of a specific year using the moment library

When it comes to determining the last day of a year, hard-coding the date as December 31st seems like a simple solution. While there are various methods using date, js, and jquery, I am tasked with working on an Angular project which requires me to use mom ...

Is Angular 4 failing to set headers properly or is Express.js searching in the wrong place?

When interacting with an Express.js API, I encountered a issue regarding the handling of auth tokens. The problem arose when sending the token in the request headers using Angular 4 compared to Postman. In Postman, setting the header named 'Authorizat ...

Error: Failed to execute close function in inappbrowser for Ionic application

Working on integrating the "in-app-browser" plugin with my Ionic project. Check out the code snippet below: const browser = this.iab.create(mylink, '_blank'); browser.on('loadstop').subscribe( data => { if ...

Substitute all properties of a specific type with a predetermined value in Typescript using recursive substitution

If we consider the given type structure: type Person = { name: string age: number experience: { length: number title: string } } Can we create a type like this: type FieldsOfPerson = { name: true age: true experience: { length: t ...

The parameter failed to initialize causing the HTTP service to fire prematurely

In my project, I am utilizing Angular 10. Within the ngOnInit function, I have nested HTTP calls structured like this: ngOnInit(): void { let communetyid; this.route.data.subscribe(data => { this.route.params.subscribe(params => { ...

Using TypeScript with React: Initializing State in the Constructor

Within my TypeScript React App, I have a long form that needs to dynamically hide/show or enable/disable elements based on the value of the status. export interface IState { Status: string; DisableBasicForm: boolean; DisableFeedbackCtrl: boolean; ...

Uncovering redundant fields in TypeScript and detecting errors through type inference

Encountering an unusual edge case with the TS compiler regarding type inference. Surprisingly, the code snippet below (with commented lines intact) should trigger a compile error, but it doesn't. interface IReturned { theField?: string; } interfa ...

Using MatTableDataSource in a different Angular component

I am working with two components, namely Order and OrderDetail. Within the Order component, I have a MatTableDataSource that gets populated from a service. OrderComponent Prior to the constructor listData: MatTableDataSource<DocumentDetailModel>; ...