如何说服TypeScript承认类型存在undefined的可能性?
如何让TypeScript识别变量可能为undefined的情况
通常我们需要告知TypeScript某个值肯定存在且不为undefined,但反过来让它承认自身类型判断过度自信的情况极为罕见。以下是具体案例:
const listA = document.querySelector(...); const listB = document.querySelector(...); while (listA.children.length > 0 || listB.children.length > 0) { const itemA: HTMLElement | undefined = listA.children[0] as any; const itemB: HTMLElement | undefined = listB.children[0] as any; // ... }
这段代码中,while循环会在至少一个列表仍有元素时持续执行,意味着当其中一个列表为空时,对应的itemA或itemB会是undefined。但TypeScript无法理解这种逻辑,始终认定两个变量一定是HTMLElement,即便强制类型断言也无法改变它的判断。
解决方法
显式添加类型守卫:在使用变量前手动检查是否为
undefined,让TypeScript重新推导类型:while (listA.children.length > 0 || listB.children.length > 0) { const itemA = listA.children[0]; const itemB = listB.children[0]; // 通过类型守卫明确分支类型 if (itemA) { // 此处itemA类型为HTMLElement itemA.remove(); } else { // 此处itemA类型为undefined console.log("listA已无元素"); } if (itemB) { // 此处itemB类型为HTMLElement itemB.remove(); } else { // 此处itemB类型为undefined console.log("listB已无元素"); } }用辅助函数包装类型推导:创建一个辅助函数,明确返回
HTMLElement | undefined类型,绕过TypeScript对children[0]的内置类型判断:function getFirstElementChild(el: ParentNode): HTMLElement | undefined { return el.children[0] as HTMLElement | undefined; } while (listA.children.length > 0 || listB.children.length > 0) { const itemA = getFirstElementChild(listA); const itemB = getFirstElementChild(listB); // 此时TypeScript会正确识别itemA、itemB可能为undefined itemA?.classList.add("processed"); }使用可选链操作符简化处理:如果仅需在后续操作中处理
undefined场景,可选链操作符?.可以让TypeScript自动识别变量的可选类型:while (listA.children.length > 0 || listB.children.length > 0) { const itemA = listA.children[0]; // 可选链会自动处理itemA为undefined的情况,TS也能识别该类型 itemA?.remove(); const itemB = listB.children[0]; itemB?.remove(); }
内容的提问来源于stack exchange,提问作者user8649828
相关产品推荐
相关产品推荐

