Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Promise.allSettled typescript array inference

I want Typescript to infer types on a filtered array.

I am filtering my results based on the status "rejected" or "fullfilled" (from Promise.allSettled).

For some reason, Typescript is not inferring my filtering results.
Here is a minimal example of what I am trying to achieve:

type FullFilledResults = {
  status: 'fullfilled';
  value: any;
}

type RejectResults = {
  status: 'rejected';
  reason: string;
}

type Results = RejectResults | FullFilledResults

const results: Results[] = [{
  status: 'rejected',
  reason: 'err'
}, {
  status: 'fullfilled',
  value: {}
}]

// Type infer Results[] but I want FullFilledResults[]
const fullfilledResults = results.filter(v => v.status === 'fullfilled')

// Type infer Results[] but I want RejectedResults[]
const rejectedResults = results.filter(v => v.status === 'rejected')
like image 379
Simon Bruneaud Avatar asked Jan 26 '23 02:01

Simon Bruneaud


2 Answers

Following function is generic for any PromiseSettled

function assertFulfilled<T>(item: PromiseSettledResult<T>): item is PromiseFulfilledResult<T> {
   return item.status === 'fulfilled';
}
like image 152
Héctor Ribes Avatar answered Feb 07 '23 08:02

Héctor Ribes


You can use type predicates for this purpose

function assertFullfilled(item: Results): item is FullFilledResults {
    return item.status === 'fullfilled';
}

const fullfilledResults = results.filter(assertFullfilled); // FullFilledResults[]
like image 44
Eugene Karataev Avatar answered Feb 07 '23 08:02

Eugene Karataev