如何使用过滤器缩小类型?

用户名

如何使用过滤器缩小类型?我很惊讶地在下面的代码中看到error具有typeOutcome和not的代码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 => ...)

此外,相关的问题:那会是更打字稿ideomatic定义ResultOutcomeErrorOutcome类和使用instanceof操盘手?

TJ人群

打字稿可以看到,error是一个ErrorOutcome如果你提供isErrorOutcome直接到filter

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

游乐场链接

显然,is ErrorOutcome方面无法在箭头函数包装器中幸免。您可以将其添加回去:

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

游乐场链接

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章