Ensure that there is at least one non-null interface member in TypeScript

Consider the following TypeScript interface:

interface MyInputInterface {
  a: A | null
  b: B | null
  aString: string | null
}

Currently, we have this function:

const hasOneNonNull = (input: MyInputInterface) => 
  input.a !== null || input.b !== null || input.aString !== null

However, this method feels fragile. It requires manual updating every time a new member is added to the interface. Is there a way to dynamically iterate through all interface members and check if at least one of them is non-null?

An ideal solution would look like this (getAllMembers is pseudo code):

const hasOneNonNull = (input: MyInputInterface) => 
  input.getAllMembers().find((elem: any) => elem !== null) !== null

Answer №1

If you need to find the values of an object in JavaScript, you should use Object.values:

const hasOneNonNull = (input: MyInputInterface) =>
  Object.values(input).reduce((hasNonNull, value) => hasNonNull || value !== null, false);

To specify that you need at least either a or b, you can utilize a union type:

type MyInputInterface =
  | { a: A; b: B | null; aString: string | null; }
  | { a: A | null; b: B; aString: string | null; }
  | { a: A | null; b: B | null; aString: string; }

You can also define the type using Typescript's mapped types:

The snippet below is referenced from this Stack Overflow answer:

interface FullMyInputInterface {
  a: A;
  b: B;
  aString: string;
}

type AtLeastOne<T, U = {[K in keyof T]: Pick<T, K> }> = Partial<T> & U[keyof U]

type MyInputInterface = AtLeastOne<FullMyInputInterface>

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

Please provide TypeScript code for a React wrapper function that augments a component's props with two additional functions

During the course of my project, I implemented a function wrapping React component to incorporate undo/redo functionality using keyboard shortcuts Ctrl+Z and Shift+Ctrl+Z. Here is an example: import React from 'react'; interface WithUndoRedoProp ...

Firebase Function deployment encountered an issue during the build phase, despite the predeploy process

My react.js project includes Firebase functions that are configured in a sub-folder called root/functions. These functions are written in typescript and have paths option set in tsconfig.json. In my functions/index.ts file, I import files from various loca ...

What are the steps to extract information from an observable?

Having trouble retrieving data from a request? I've encountered an issue where the data retrieved inside .subscribe in an observable function is returning as undefined when trying to access it outside the function. It's quite frustrating! Here i ...

Leveraging SPFx with @pnp/sp for list creation

Currently, I am attempting to create a custom list using @pnp/sp. In my process, it is necessary for me to verify if the list already exists. If it does not exist, then I will proceed to create the list and add its columns accordingly. The issue lies in t ...

Waiting for an Angular Observable to complete its process

I have recently developed a small Angular application that retrieves data from a REST API using observables. However, I am facing an issue with their asynchronous nature. let tempArray: boolean[] = []; for (let i = 0; i < 3; i++) { this._myservice. ...

Error: Unable to access $rootScope in the http interceptor response function

I have set up an interceptor to display an ajax spinner while loading. interface IInterceptorScope extends angular.IRootScopeService { loading: number; } export class Interceptor { public static Factory($q: angular.IQService, $ro ...

Converting Object-Oriented Programming to Functional Programming in JavaScript

My JavaScript code looks like this: function stringFormatter(locale) { return { getA: function() { return 'A' + locale; }, getB: function() { return 'B' + locale; }, getC: function() { return &apo ...

The styled component is not reflecting the specified theme

I have a suspicion that the CSS transition from my Theme is not being applied to a styled component wrapped in another function, but I can't pinpoint the exact reason. I obtained the Basic MUI Dashboard theme from this source and here. Initially, inte ...

Get the HTML file converted to a DOCX format that is compatible with Mac Pages

I am currently working on a Next.js application using TypeScript, and I want to give users the ability to download a page as a DOCX file. Initially, I was excited to discover that this could be easily accomplished by following this method. However, after ...

When switching tabs, Ion-select should not reload the selected name

Whenever I switch tabs and then return to the previous tab in Ionic, the select field that was previously set becomes null, even though the page is still loading and the variable is populated. <ion-header color="primary"> <ion-navbar> &l ...

Executing cypress tests with tags in nrwl nx workspace: A simple guide

Currently, I am working within a nrwl nx workspace where I have set up a cypress BDD cucumber project. My goal is to run cypress tests based on tags using nrwl. In the past, I would typically use the "cypress-tags" command to achieve this. For example: &q ...

Getting started with installing Bootstrap for your Next.Js Typescript application

I have been trying to set up Bootstrap for a Next.js Typescript app, but I'm having trouble figuring out the proper installation process. This is my first time using Bootstrap with Typescript and I could use some guidance. I've come across these ...

Using TypeScript generics to define function parameters

I'm currently working on opening a typescript method that utilizes generics. The scenario involves an object with different methods, each with specified types for function parameters. const emailTypes = { confirmEmail: generateConfirmEmailOptions, / ...

Troubleshooting Type Error in React with Typescript: Finding Solutions for HTMLButtonElement Issue

Hey there! I recently created a TodoList Sample using React, Redux, Typescript, and SCSS. However, I encountered an issue with Typescript error which states the following: Error Status: Type '(event: { target: HTMLButtonElement; }) => void' ...

Angular2: Determining which checkboxes have been selected

Currently, I am utilizing angular2 and have the following HTML code: <div *ngFor="let val of channelForTabs; let i=index"> <label for="isCheckBox" style="margin-left:15px;">Draw</label> <input id="checkBox{{i}} ...

Blank webpage caused by ngx TranslateService

Every time I attempt to translate Angular components using ngx-translate/core by utilizing the translateService in the constructor, the page appears blank. This is my appModule : import { NgModule } from '@angular/core'; import { BrowserModule } ...

Tips for including a property type description to enable visibility in VSCode's intellisense

I'm working on creating a reusable type that is used as arguments in several functions. However, I've noticed that intellisense only displays descriptions added to interfaces and not the original type declaration. For example, why does the descr ...

Issue encountered with the signature provided for a Safe API POST request

Watch this demonstration video of the issue at hand: I have created a signer using my Metamask Private Key and generated a signature from it as shown below: const signer = new ethers.Wallet(PRIVATE_KEY as string, provider) const safeInstance = new ethers. ...

"Is there a way to generate a Date Object without including the time component while utilizing the format YYYY-MM-DD within

I'm struggling to generate a Date object with just the date when using 'YYYY-MM-DD' input format. Here's the code I'm using: let date1 = new Date('2022-01-06') let date2 = new Date('01/06/2022') The results ar ...

Setting up TypeScript compilation for TS modules in an AngularJs application: A comprehensive guide

After conducting a test, it has come to my attention that TypeScript 2.6.2 imposes a requirement where imported elements need to be used in a new before the module is referenced in a require. The test is based on the following code snippets extracted from ...