我最近遇到了一个问题,TypeScrip错误地认为变量可以是undefined
.这是一个简化版本:
const f = (a?: boolean, b?: boolean) => {
if (!a && !b) return;
let c: boolean;
if (a) c = false;
else c = b;
}
在else c = b;
行中,a
是false
或undefined
,b
只能是true
,否则!a && !b
就会为真.但TypeScrip抛出了一个错误,说:
Type 'boolean | undefined' is not assignable to type 'boolean'.
个
为了暂时解决这个问题,我在if (a) c = false;
行中添加了|| !b
:
const f = (a?: boolean, b?: boolean) => {
if (!a && !b) return;
let c: boolean;
if (a || !b) c = false;
else c = b;
}
但我很好奇为什么会发生这个错误,而且TypeScrip无法检测到变量不能为undefined
.