【发布时间】:2023-01-18 21:11:21
【问题描述】:
只是作为这个问题的序言 - 我可能错过了一些东西:)
我有以下代码:
function test(a: number | undefined, b: number | undefined) {
if (!a && !b) {
console.log('Neither are present');
return;
}
if (!b && !!a) {
console.log('b is not present, we only found a - do a thing with a');
return;
}
if (!a && !!b) {
console.log('a is not present, we only found b - do a thing with b');
return;
}
// At this point, I'd like the compiler to know that both a and b are not undefined,
// but it doesn't.
console.log(a + b);
}
编译器在最后一行出现错误消息 'a' is possibly 'undefined' 和 'b' is possibly 'undefined'。
但是,如果 a 和 b 都存在(即未定义),代码就不可能达到这一点。
我的 if 语句比您预期的更复杂(即我有 !a && !!b 而不仅仅是 !a),因为如果其他参数不存在,我想使用现有参数。
我错过了什么,是否有更多类型化的方式来编写此逻辑?
谢谢。
【问题讨论】:
标签: typescript