【发布时间】: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