首页 > 解决方案 > 在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之类的东西是可行的,但对于绕过这个问题的新包来说似乎有点矫枉过正。

期待一些帮助!

安德烈亚斯

标签: typescripttypes

解决方案


我能想出的最佳解决方案是使用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) 

推荐阅读