Promise.allSettedd打字稿数组推断

时间:2020-04-30 17:08:54

标签: javascript typescript promise type-inference

我希望Typescript推断过滤数组上的类型。

我正在根据状态“已拒绝”或“已满”(来自Promise.allSettled)过滤结果。

由于某种原因,Typescript无法推断我的过滤结果。
这是我要实现的目标的最小示例:

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

2 个答案:

答案 0 :(得分:1)

您可以为此使用类型谓词

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

const fullfilledResults = results.filter(assertFullfilled); // FullFilledResults[]

答案 1 :(得分:1)

以下函数对于任何 PromiseSettled 都是通用的

function assertFulfilled<T>(item: PromiseSettledResult<T>): item is PromiseFulfilledResult<T> {
   return item.status === 'fulfilled';
}