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 for inserting a string into an array nested within an object stored in a state array

Currently, the variable sizeVariant is a string array and I am trying to append strings to it using an onClick event. The function findIndex seems to be working fine. However, there seems to be an issue with the concatenation section. It appears that using ...

Monitor the change in values upon pressing the submit button on Angular

I am currently working with an edit form that contains data in the input fields. <ng-form #infoForm="ngForm" novalidate> <div> <label for="firstName">First Name :</label> <input type=" ...

Tips for resolving this unhandled error in React TypeScript

After creating a program in React TypeScript, I encountered an uncaught error. Despite running and debugging tests and conducting extensive research on Google, I have been unable to resolve this issue on my own. Therefore, I am reaching out for assistance ...

Mastering Angular 7: A guide to efficiently binding values to radio buttons

Struggling to incorporate radio buttons into my project, I encountered an issue where the first radio button couldn't be checked programmatically. Despite attempting the suggested Solution, it didn't resolve the problem within my code. Below is ...

Error TS2309: TypeScript encountered an error in Types/node/index.d.ts

I recently upgraded my .Net Core Angular 2 project using SystemJs from Typings to @Types. The entire project has been rebuilt with the latest VS tooling for .Net Core 1.0.1, TypeScript 2.0.10, and Node.js 7.0.0 as of 12/21/2016. Everything was working fi ...

Using Typescript: Defining a function parameter that can be either of two interfaces

While browsing through this specific question, I noticed that it was somewhat related to my current issue, although there were notable differences. In my scenario, I have a function named parseScanResults which accepts an object as its argument. This obje ...

Develop a "Read More" button using Angular and JavaScript

I am in search of all tags with the class containtText. I want to retrieve those tags which have a value consisting of more than 300 characters and then use continue for the value. However, when I implement this code: <div class=" col-md-12 col-xl-12 c ...

Displaying inner arrays in an Angular2 MatTable

Welcome to my initial post on Stack Overflow, where I hope to communicate my query clearly. I am currently attempting to develop a table with dynamic columns. However, I am encountering difficulty in comprehending how to bind matColumnDef to a specific el ...

A guide on extracting a JSON data with a BigInt type using TypeScript

I am facing an issue with parsing a bigint from a JSON stream. The value I need to parse is 990000000069396215. In my TypeScript code, I have declared this value as id_address: bigint. However, the value gets truncated and returns something like 9900000000 ...

The user interface design transforms as a PDF file is being generated through html2pdf

I am experiencing an unusual problem while using html2pdf to convert an HTML page to a PDF file and download it. The conversion process is successful and the PDF file is downloaded without any issues. However, when I click on a button to generate the file, ...

Creating keys from extensive JSON data without having to manually match types using Typescript

Is there a way to efficiently parse and access the values in large JSON files using Typescript, without the need to manually define interfaces for all expected key/value pairs? In the past, working with small JSON files required only extracting a few spec ...

Having trouble retrieving a specific key from the state object in Redux using TypeScript

I have incorporated TypeScript into my Ionic project, using React hooks. I recently added an errorReducer to handle any errors that may arise from the server. Below is a snippet of my code: Action import { ERROR_OCCURRED } from "./types"; ...

What is the process for integrating TypeScript compiling into a JavaScript application?

My project includes a build.js file that is responsible for building the project. It has two main objectives: Compile .ts files and store them in a new directory. Create an asar archive containing the compiled files. Since typescript (or tsc) is availabl ...

TypeScript async function that returns a Promise using jQuery

Currently, I am facing a challenge in building an MVC controller in TypeScript as I am struggling to make my async method return a deferred promise. Here is the signature of my function: static async GetMatches(input: string, loc?: LatLng):JQueryPromise& ...

I'm looking for the Type Definitions Files (*.d.ts) for the Amazon Cognito Identity SDK. Does anyone know where I can find them and how

Where can I locate Type Definitions Files (*.d.ts) for the Amazon Cognito Identity SDK and how can I use them? I am utilizing TypeScript for Angular2 and I would like to have the code assistant readily available when implementing "AWS Cognito." While I al ...

Determining the instance type of a TypeScript singleton class

I have a unique singleton implementation: class UniqueSingleton { private static instance: UniqueSingleton; private constructor() { // Only allows instantiation within the class } public static getInstance(): UniqueSingleton { if (!Unique ...

Having trouble locating the name 'it' in Jest TypeScript

After setting up Jest in React + TypeScript, I encountered an error when trying to run a test using the command npm test. The error message displayed was: Cannot find name 'it'. Do you need to install type definitions for a test runner? Try ` ...

Using href with IconButtonProps is not supported

I'm facing a challenge in creating a wrapper for the IconButton. I aim to pass components or href props, but unfortunately, I am unable to achieve this by passing the IconButtonProps. Is there a way to accomplish this? function CustomIconButton(props ...

Utilize the nests cli swagger plugin to enable compatibility with external models

Exploring the functionality of the swagger plugin provided by nestjs, I am eager to try it out. While it works smoothly when defining a class like CreateUserDto, my goal is to incorporate types from a third-party library - specifically @adyen/api-library. ...

How to minimize xAxes labels in Chart.js

As a newcomer to Chart.js, I am encountering some challenges. My goal is to create a bar chart that displays hourly information. However, when attempting to show data for a week, a month, or an extended period, I face issues with reducing the labels on the ...