Home > Back-end >  Gaurd on mixed array type
Gaurd on mixed array type

Time:08-22

I have an array of loaders which can be either query or proxy. I want to create a gaurd that states that each entry is in the "success" state. I tried this:

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 it's not working. Is it possible to use guards with mixed array types?

CodePudding user response:

It's rather straightforward with generics and intersection types:

function isLoaded<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 array: (Query | Proxy)[] = [];

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

TS Playground

  • Related