Guard against an array that contains different data types

I am trying to create a guard that ensures each entry in an array of loaders, which can be either query or proxy, is in the "success" state. Here is my attempted solution:

type LoadedQueryResult = Extract<UseQueryResult, { status: 'success' }>;
type LoadedProxyResult = Extract<UseProxyResult, { status: 'success' }>;
 
function isLoaded<T extends Array<UseQueryResult | UseProxyResult>>(loaders):
  loaders is Array<LoadedQueryResult | LoadedProxyResult>
{
    return loaders.every(loader => loader.status === 'success')
}

However, I am encountering issues with this approach. Can guards be utilized with mixed array types?

Answer №1

Utilizing generics and intersection types makes it a simple process:

function isFullyLoaded<T extends {status: string}>(loaders: T[]): loaders is (T & {status: 'success'})[] {
    return loaders.every(loader => loader.status === 'success');
}

/**********************/

type Query = {status: 'success' | 'error', foo: number};
type Proxy = {status: 'success' | 'error', bar: number};

let dataArr: (Query | Proxy)[] = [];

dataArr[0].status; // 'success' | 'error'
if (isFullyLoaded(dataArr)) {
    dataArr[0].status; // 'success'
}

TS Playground

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

Tips on updating x-label formatting (to display months in words) utilizing morris.js with Angular 5

Snapshot of my Request. I'm looking to alter the xLabel (2018-01 - to - Jan) and I am utilizing morris.js. ...

Angular 2 Component attribute masking

In my Angular 2 component called Foobar, I have defined a property named foobar: import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-foobar', templateUrl: './foobar.component ...

What is the best way to reference typescript files without using absolute paths?

As typescript does not seem to have built-in support for absolute path references (according to this GitHub issue), it becomes difficult to organize and maintain my file references. With TypeScript files scattered across various locations in my folder stru ...

Unable to locate the name 'Cheerio' in the @types/enzyme/index.d.t file

When I try to run my Node application, I encounter the following error: C:/Me/MyApp/node_modules/@types/enzyme/index.d.ts (351,15): Cannot find name 'Cheerio'. I found a suggestion in a forum that recommends using cheerio instead of Cheerio. H ...

TypeScript is throwing an error because a value has been declared but never actually used in the

private tree_widget: ITreeWidget; private $ghost: JQuery | null; private drag_element: DragElement | null; private previous_ghost: IDropHint | null; private open_folder_timer: number | null; constructor(tree_widget: ITreeWidget) { this.tree_widget = t ...

How can I determine which dist folder is utilized during the building of my App if an npm package contains multiple dist folders?

I have integrated an npm package called aurelia-google-maps into my application. This package includes various distribution folders such as AMD, System, CommonJS, Native Modules, and ES2015 within the /node_modules/ directory like so: /node_modules/ /a ...

Importing CSS properties from MUI v5 - A comprehensive guide

I'm working with several components that receive styles as props, such as: import { CSSProperties } from '@material-ui/styles/withStyles' // using mui v4 import because unsure how to import from v5 paths import { styled } from '@mui/mat ...

Modify a property within an object and then emit the entire object as an Observable

I currently have an object structured in the following way: const obj: SomeType = { images: {imageOrder1: imageLink, imageOrder2: imageLink}, imageOrder: [imageOrder1, imageOrder2] } The task at hand is to update each image within the obj.images array ...

What is the best way to structure a nested object model in Angular?

Issue occurred when trying to assign the this.model.teamMembersDto.roleDto to teamMembersDto. The error message states that the property roleDto does not exist on type TeamMembersDropdownDto[], even though it is nested under teamMembersDto. If you look at ...

Angular 4: Utilizing a class with a constructor to create an http Observable model

Within my application, I have a Class model that is defined with a constructor. Here is an example: export class Movie { title: string; posterURL: string; description: string; public constructor(cfg: Partial<Movie>) { Object ...

Managing event date changes in Angular PrimeNG FullCalendar

Is there a way to capture an event when the date of an event is changed? I would like to receive the new date in a function. Is this functionality possible? For example, if I have an event scheduled for 2020-01-01 and I drag it to date 2020-01-10, how can ...

The instanceof operator does not recognize the value as an instance and is returning false, even though it

Is there a method to verify the current instance being used? This is what I am logging to the console: import { OrthographicCamera } from 'three'; // Later in the file: console.log(camera instanceof OrthographicCamera, camera); and the result ...

Encountering an issue in Angular 4 AOT Compilation when trying to load a Dynamic Component: Error message states that the

My Angular application is facing challenges when loading dynamic components. Everything works smoothly with the JIT ng serve or ng build compilation. Even with AOT ng serve --prod or ng build --prod, I can still successfully build the application. Lazy loa ...

What is the reason for Google Chrome extension popup HTML automatically adding background.js and content.js files?

While using webpack 5 to bundle my Google Chrome extension, I encountered an issue with the output popup HTML. It seems to include references to background.js and content.js even though I did not specify these references anywhere in the configuration file. ...

Issue encountered when attempting to develop a countdown timer using Typescript

I am currently working on a countdown timer using Typescript that includes setting an alarm. I have managed to receive input from the time attribute, converted it using .getTime(), subtracted the current .getTime(), and displayed the result in the consol ...

Tips for isolating data on the current page:

Currently, I am using the igx-grid component. When retrieving all data in one call and filtering while on the 3rd page, it seems to search through the entire dataset and then automatically goes back to "Page 1". Is there a way to filter data only within th ...

Unable to access the correct item from local storage while a user is authenticated

I am facing an issue with retrieving the userid from local storage when a user is authenticated or logged in. The user id is not being fetched immediately upon logging in, and even when navigating from one page to another, it remains unavailable until I re ...

Error message: "react-router typescript navigation version 0.13.3 - Unable to access 'router' property"

I'm currently in the process of porting an existing React project to TypeScript. Everything seems to be going smoothly, except for the Navigation mixin for react-router (version 0.13.3). I keep encountering an error message that says "Cannot read prop ...

Creating custom disabled button styles using TailwindUI in a NextJS application

I had a NextJS application that utilized Atomic CSS and featured a button which becomes disabled if a form is left unfilled: <Button className="primary" onClick={handleCreateCommunity} disabled={!phone || !communi ...

Is it feasible to obtain the userId or userInfo from the Firebase authentication API without requiring a login?

Is it feasible to retrieve the user id from Firebase authentication API "email/password method" without logging in? Imagine a function that takes an email as a parameter and returns the firebase userId. getId(email){ //this is just an example return t ...