【发布时间】: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 => ...)
还有一个相关的问题:将ResultOutcome 和ErrorOutcome 定义为类并使用instanceof 运算符来代替Typescript 是否更符合思想?
【问题讨论】:
-
我想,this post 包含,你想要什么
标签: typescript