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. 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?
CodePudding user response:
Since you're using tabReport in a callback function, typescript doesn't know whether that code will execute synchronously or asynchronously. If it happens asynchronously, and if tabReport is a let (or var), then the value might change by the time it runs. So as far as typescript can tell, the value might become undefined by the time the function runs.
The simplest fix for this is just to make tabReport a 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 = getTabReportbyType(tabId, view);
const tabConst = tabReport;
if (tabConst !== undefined) {
setTabReports(prevMap => new Map(prevMap.set(tabId, tabConst)));
}
