0

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.

James
  • 1,335
  • 1
  • 10
  • 19
  • Use a local variable for `menuItemList[i]` and control flow should be able to follow the check – Titian Cernicova-Dragomir May 30 '19 at 12:44
  • Do you think there is a way to do this without resorting to that? Also, why does your solution work? – James May 30 '19 at 13:43
  • 1
    This is a [bug](https://github.com/microsoft/TypeScript/issues/28081) and it should hopefully be [fixed](https://github.com/microsoft/TypeScript/pull/31478) for TS3.6. – jcalz May 30 '19 at 14:16
  • @jcalz I'm not sure how that bug is related? My code works the same using `['value']` or `.value` – James May 30 '19 at 14:54

0 Answers0