【发布时间】:2020-12-18 18:07:28
【问题描述】:
我实际上遇到了一个有趣的问题。
我希望有以下行为:
- 如果 err 为 null 则需要结果,因为我返回它
- 如果 err 不为 null,则 result 是可选的,因为我将返回我的错误
const callback = <ErrorType extends Error | null>(err: ErrorType, result?: (ErrorType extends null ? number : undefined)): Error | number => {
if (err) {
return err;
}
return result;
}
我知道这个回调没用,但条件必需参数很有趣:)
其实我有两个错误:
Type 'Error | null' is not assignable to type 'number | Error'.
Type 'null' is not assignable to type 'number | Error'.
Type 'ErrorType' is not assignable to type 'Error'.
Type 'Error | null' is not assignable to type 'Error'.
Type 'null' is not assignable to type 'Error'.
return err;
和
Type '(ErrorType extends null ? number : undefined) | undefined' is not assignable to type 'number | Error'.
Type 'undefined' is not assignable to type 'number | Error'.
return result;
我真的不明白为什么会出现这些错误。
问题是,如果我遇到错误,我将永远不会返回结果,并且我之前使用if (err) 验证该错误不为空,所以我无法返回空。
数字也一样,有了我的扩展,我确信数字永远不会未定义......
我认为这是一个推理问题。我在做坏事,但我不知道在哪里。
谢谢你:P
【问题讨论】:
标签: typescript type-inference typescript-generics