[英]why is typescript returning this compile error even though the code is checking for undefined?
I think that usually if code has a guard in place to check for an "undefined" value as shown below, then there should be no issue with code like line 249 below, since the undefined value was already guarded/validated.我认为通常如果代码有一个保护来检查“未定义”值,如下所示,那么像下面的第 249 行这样的代码应该没有问题,因为未定义的值已经被保护/验证。 However, I'm getting the following error below, despite the guard:
但是,尽管有警卫,但我在下面收到以下错误:
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 | }
Any idea why the Typescript compiler is returning an error for this particular scenario?知道为什么 Typescript 编译器会针对这种特定情况返回错误吗?
Since you're using tabReport
in a callback function, typescript doesn't know whether that code will execute synchronously or asynchronously.由于您在回调 function 中使用
tabReport
,因此 typescript 不知道该代码是同步执行还是异步执行。 If it happens asynchronously, and if tabReport
is a let
(or var
), then the value might change by the time it runs.如果它是异步发生的,并且如果
tabReport
是一个let
(或var
),那么值可能会在它运行时发生变化。 So as far as typescript can tell, the value might become undefined
by the time the function runs.因此,据 typescript 所知,在 function 运行时,该值可能会变得
undefined
。
The simplest fix for this is just to make tabReport
a const
:最简单的解决方法就是让
tabReport
成为const
:
const tabReport = getTabReportByType(tabId, view);
// rest is same as before
If the tabReport
variable is serving some other purpose and you need to keep it a let
, you could have an extra variable which is a const:如果
tabReport
变量用于其他目的,并且您需要将其保留为let
,则可以有一个额外的变量,它是一个 const:
tabReport = getTabReportbyType(tabId, view);
const tabConst = tabReport;
if (tabConst !== undefined) {
setTabReports(prevMap => new Map(prevMap.set(tabId, tabConst)));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.