typescript - 在Typescript中按索引访问时如何处理潜在的空数组
问题描述
当数组也可以为空时,在Typescript中通过索引访问元素的首选方法是什么,导致元素是undefined
?
我正在使用 Typescript 在 React 中编写一个简单的游戏,其中我有一个game
由 type 集数组组成的变量ISet
。在这个简化的示例中,它的界面中ISet
有一个score
属性,我尝试访问它
const game: ISet[] = [];
const currentSet = game[game.length - 1]; // 'currentSet' will be of type 'ISet', although it will be 'undefined' here
console.log(currentSet.score); // No Typescript error, although a 'Uncaught TypeError: Cannot read property 'score' of undefined' error will be thrown when run
我怎样才能让 Typescript 检测到currentSet
可能在undefined
这里?
我试图手动将currentSet
's type 设置为
const currentSet: ISet | undefined = game[game.length - 1];
但这不起作用,并将类型声明更改为
const game: Array<ISet | undefined> = [];
允许undefined
添加到数组中,这不是我想要的,以后会导致问题。
我已经阅读了几个 GitHub 问题, 比如这个,但找不到任何关于解决方法的建议。使用Underscore 中的 last之类的东西是可行的,但对于绕过这个问题的新包来说似乎有点矫枉过正。
期待一些帮助!
安德烈亚斯
解决方案
我能想出的最佳解决方案是使用lodash 中的 last并将其添加为单独的 package。我还通过安装单独添加了类型定义@types/lodash.last
。
我上面的示例案例最终看起来像这样:
import last from 'lodash.last'
const game: ISet[] = [];
const currentSet = last(game); // 'currentSet' now has a type of 'ISet | undefined'
console.log(currentSet.score); // Object is possibly 'undefined'. ts(2532)
推荐阅读
- reactjs - 如何更改 React-TinyMCE 中的默认语言?
- amazon-web-services - CloudFront 将自定义标头转发到 Origin 但具有空值
- c++ - 复制构造函数如何执行?
- python-3.x - Python 中的 SimpleITK.ImageFileWriter 没有方法“SetImageIO”,但 C++ 文档说它有
- html - 如何在 R 中打印 HTML
- c# - 为什么 Jarray 添加重复的作业?
- c - 如果我们在 C 中的调用函数中不使用 return 语句会发生什么?
- c - 为什么只有在选择数组是3或7个元素时才发生分割故障?
- apache - 如何管理安装到 docker 容器中的卷的权限?
- css - Bootstrap 卡在图像周围有白色修剪