I tried using if to determine if the attribute exists, but got an error
I tried, why is that?
CodePudding user response:
Typescript doesn't know that the forEach
callback function is executed synchronously. So it can't guarantee that when the function passed to forEach
is executed, that the check still applies.
The simplest way around this is to use a for/of loop instead which is guaranteed to be executed synchronously.
if (a.childList) {
for (const b of a.childList) {
for (const c of a.childList) {
console.log(b, c) // works
}
}
}
CodePudding user response:
This is because of unrelability of when function could be called.
Consider this, the the #forEach
accepts a function. As a result, there is no proper way for compiler to determine whether the value would have changed or not before function is called.
E.g.:
if (a.childList) {
a.childList.forEach(() => {
a.childList.forEach(() => {});
a.childList = null
});
}
In above case, in the first iteration only, I have changed the value, so now at runtime it may crash because of this. Since, typescript is not aware of your function execution flow, it requires you to check the nullabliity again in a function call inorder to avoid any runtime errors.
You can change your code as follow to fix it:
const {childList} = a
if (childList) {
childList.forEach(() => {
childList.forEach(() => {});
});
}
CodePudding user response:
You can use optional chaining to avoid the error altogether:
a.childList?.forEach(() => {
a.childList?.forEach(() => {});
});
This will achieve the same effect as your if
check.