为什么typescript会返回这个编译错误,即使代码正在检查是否未定义



我认为,通常如果代码有一个保护程序来检查;未定义的";值,那么像下面第249行这样的代码应该没有问题,因为未定义的值已经被保护/验证了。然而,尽管有防护措施,我还是收到了以下错误:

Argument of type 'Element | undefined' is not assignable to parameter of type 'Element'.
Type 'undefined' is not assignable to type 'ReactElement<any, any>'.  TS2345
247 |           tabReport = getTabReportByType(tabId, view);
248 |           if(tabReport != undefined){
> 249 |               setTabReports(prevMap => new Map(prevMap.set(tabId, tabReport)));
|                                                                   ^
250 |           }
251 |       }
252 |   }

你知道为什么Typescript编译器在这个特定的场景中返回错误吗?

由于在回调函数中使用tabReport,typescript不知道该代码是同步执行还是异步执行。如果它是异步发生的,并且tabReportlet(或var(,那么该值可能会在运行时发生变化。因此,根据typescript的判断,到函数运行时,该值可能会变成undefined

对此,最简单的修复方法就是将tabReport设置为const:

const tabReport = getTabReportByType(tabId, view);
// rest is same as before

如果tabReport变量有其他用途,并且您需要将其保持为let,那么您可以有一个额外的变量,它是const:

tabReport = getTabReportbyType(tabId, view);
const tabConst = tabReport;
if (tabConst !== undefined) {
setTabReports(prevMap => new Map(prevMap.set(tabId, tabConst)));
}

最新更新