Typescript 如何使用过滤器进行类型缩小?
如何使用过滤器实现类型缩小?我惊讶地看到,在下面的代码中,Typescript 如何使用过滤器进行类型缩小?,typescript,Typescript,如何使用过滤器实现类型缩小?我惊讶地看到,在下面的代码中,error的类型是output,而不是erroroutput type Outcome = ResultOutcome | ErrorOutcome; type ResultOutcome = { id: string; result: string; }; type ErrorOutcome = { id: string; error: string; }; function isErrorOutcome(val: O
error
的类型是output
,而不是erroroutput
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会更具意识形态吗?如果直接向过滤器
:
results.filter(isErrorOutcome).forEach(error => ...)
显然,是erroroutput
方面在arrow函数包装器中无法生存。您可以将其添加回:
results.filter((result): result is ErrorOutcome => isErrorOutcome(result)).forEach(error => ...);
我想,它包含了你想要的东西