使用可选键对对象进行TypeType严格Null检查

时间:2019-05-30 12:39:35

标签: typescript strictnullchecks

我在Angular项目中引入了strictNullchecks编译器选项,并且遇到了这个问题。

  

错误TS2345:“字符串|类型”的参数未定义”不能分配给“字符串”类型的参数。

  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;
    }

在上面的代码中,我在使用menuItemList[i].route之前先检查是否已定义,但是仍然出现上面概述的错误。

如果我将其强制转换为string,那么它将解决此问题,但是我认为这是一个不好的解决方法,因为我已经确认它不能undefined if语句,因此它必须string类型。

我认为问题可能与MenuItem.route?是可选的事实有关,但由于我前面提到的原因,undefined不能成为if,所以看不到这是为什么tar --sort=name --owner=root:0 --group=root:0 --mtime='UTC 2019-01-01' ... 检查。

0 个答案:

没有答案
相关问题