I am introducing the strictNullchecks
compiler option in our Angular project and have come across this issue.
error TS2345: Argument of type 'string | undefined' is not assignable to parameter of type 'string'.
replaceTokens(menuItemList: MenuItem[]): MenuItem[] {
for (let i = 0; i < menuItemList.length; i++) {
if (menuItemList[i].route) {
menuItemList[i].route = this.tokenizer.replace(
menuItemList[i].route <-- Error here
// menuItemList[i].route as string <-- No error here
);
}
}
return menuItemList;
}
In the code above I am checking that menuItemList[i].route
is defined before using it, however I am still getting the error outlined above.
If I were to cast it to a string
then it would solve the issue, but I think that is a bad work around as i've already confirmed that it can't be undefined
in the if statement so it must be the string
type.
I believe the issue could be to do with the fact that MenuItem.route?
is optional, but can't see why that's a problem as I have previously mentioned it can't be undefined
due to the if
check.