【问题标题】:Typescript Object is possibly null even inside an if statement checking that the object is not null即使在检查对象不为空的 if 语句中,Typescript Object 也可能为空
【发布时间】:2021-07-13 23:06:02
【问题描述】:

我正在尝试根据提供的索引访问数组内部对象的属性,即使我检查该对象不为空,打字稿仍然抱怨它可能为空。

“selectedIndex”实际上也是我项目中的一个反应状态。

const arrayOfObjects: {bar:{baz: string; qux: string;}}[] = [{bar: {baz: 'value', qux: 'value'}}];

let selectedIndex: number = 0; //can be changed

if (arrayOfObjects[selectedIndex].bar !== null) {
  doSomethingWith(arrayOfObjects[selectedIndex].bar.baz);
  // here there will be a typescript error saying that "bar" Object is possibly null
}

有什么想法吗?

【问题讨论】:

  • 我无法重现该问题。你用的是什么版本的TS?会不会是IDE缓存问题?
  • 也许如果 (arrayOfObjects[selectedIndex] && arrayOfObjects[selectedIndex].bar !== null)
  • 我正在使用 typescript ~3.7.2 和 react-scripts 4.0.3,我会尝试更新它。谢谢!
  • 升级到 typescript 4.3.0,还是一样的问题
  • 问题是我将索引保存到反应状态,显然这可以在 if 语句中评估项目和语句返回的内容之间发生变化。

标签: javascript typescript


【解决方案1】:

错误是由于 selectedIndex 是一个反应状态值,可以在语句之间更改

let var = arrayOfObjects[selectedIndex].bar;   
if (var) { 
  doSomething(var.baz) 
}

【讨论】:

  • 它似乎是 tsc 本身,我的 package.json 中没有“干净”命令,知道 yarn 是否有等价物吗?另外,不确定这是否重要,但在我的代码中,“selectedIndex”实际上是反应功能组件中的一个状态,使用 useState 钩子创建。
  • 啊……状态值是否可能由于反应魔法而在 if 和 next 之间发生变化?试试let var = arrayOfObjects[selectedIndex].bar; if (var) { doSomething(var.baz) }
  • 这正是问题所在,不知道 React 可以做到这一点,我使用了你建议的修复方法,它成功了!请将其编辑为您的答案,以便我可以将其选为接受的答案。
猜你喜欢
  • 1970-01-01
  • 2020-02-27
  • 2016-02-01
  • 2019-11-10
  • 1970-01-01
  • 2018-08-06
  • 2017-05-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多