typescript中if判断非空的变量依然会被报错variable is possibly undefined

demo: typescript playground demo

主要代码:

interface Example {
  children?: Example[]
}

const example: Example = { children: [{ children: [] }] }

if (example.children) {
  for (let i = 0; i < example.children.length; i++) {
    if (example.children[i] && example.children[i].children) {
      console.log(example.children[i].children.length)
    }
  }
}

if判断example.children[i].children非空后 下一句依然提示example.children[i].children is possibly undefined
请问为何会出现这种情况 如何能在不使用强制非空断言的情况下解决这个问题?

阅读 3k
2 个回答
var item = example.children[i];
if (item.children) {
  console.log(item.children.length)
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题