如何使用过滤器缩小类型?我很惊讶地在下面的代码中看到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定义ResultOutcome
和ErrorOutcome
类和使用instanceof
操盘手?
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句