【问题标题】:How to use filter for type narrowing? [duplicate]如何使用过滤器进行类型缩小? [复制]
【发布时间】:2020-10-26 16:49:58
【问题描述】:

如何使用过滤器实现类型缩小?我很惊讶在下面的代码中看到 error 的类型是 Outcome 而不是 ErrorOutcome

type Outcome = ResultOutcome | ErrorOutcome;
type ResultOutcome = {
  id: string;
  result: string;
};
type ErrorOutcome = {
  id: string;
  error: string;
};

function isErrorOutcome(val: Outcome): val is ErrorOutcome {
  return (val as ErrorOutcome).error !== undefined
}

function isResultOutcome(val: Outcome): val is ResultOutcome {
  return (val as ResultOutcome).result !== undefined
}

results.filter(result => isErrorOutcome(result)).forEach(error => ...)

还有一个相关的问题:将ResultOutcomeErrorOutcome 定义为类并使用instanceof 运算符来代替Typescript 是否更符合思想?

【问题讨论】:

  • 我想,this post 包含,你想要什么

标签: typescript


【解决方案1】:

如果您将isErrorOutcome 直接提供给filter,TypeScript 可以看到errorErrorOutcome

results.filter(isErrorOutcome).forEach(error => ...)

Playground link

显然is ErrorOutcome 方面无法在箭头函数包装器中生存。不过,您可以将其添加回来:

results.filter((result): result is ErrorOutcome => isErrorOutcome(result)).forEach(error => ...);

Playground link

【讨论】:

    猜你喜欢
    • 2021-10-21
    • 2010-10-03
    • 2015-10-02
    • 2012-05-10
    • 2015-01-31
    • 1970-01-01
    • 2020-03-19
    • 1970-01-01
    • 2020-06-15
    相关资源
    最近更新 更多