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')
Following function is generic for any PromiseSettled
function assertFulfilled<T>(item: PromiseSettledResult<T>): item is PromiseFulfilledResult<T> {
return item.status === 'fulfilled';
}
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[]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With