最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Promise.allSettled typescript array inference - Stack Overflow

programmeradmin0浏览0评论

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')

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')
Share Improve this question edited Apr 30, 2020 at 17:20 Simon Bruneaud asked Apr 30, 2020 at 17:08 Simon BruneaudSimon Bruneaud 2,5673 gold badges15 silver badges27 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 17

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[]
发布评论

评论列表(0)

  1. 暂无评论