在 Typescript 中按索引访问时如何处理潜在的空数组

And*_*man 6 types typescript

当数组也可以为空时,在 Typescript 中通过索引访问数组中的元素的首选方法是什么undefined

我正在使用 Typescript 在 React 中编写一个简单的游戏,其中有一个由gametype 集合数组组成的变量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
Run Code Online (Sandbox Code Playgroud)

我怎样才能让 Typescript 检测到这里currentSet可能存在undefined

我尝试手动将 的currentSet类型设置为

const currentSet: ISet | undefined = game[game.length - 1];
Run Code Online (Sandbox Code Playgroud)

但这不起作用,并将类型声明更改为

const game: Array<ISet | undefined> = [];
Run Code Online (Sandbox Code Playgroud)

允许undefined添加到数组中,这不是我想要的,并且会在以后导致问题。

我已经阅读了几个 GitHub 问题, 例如这个问题,但找不到任何有关解决方法的建议。使用Underscore 中的最后一个类似的东西是可行的,但对于一个新的包来绕过这个问题似乎有点过分了。

期待一些帮助!

安德烈亚斯

H.B*_*.B. 5

noUncheckedIndexedAccessTypeScript > v4.1 具有应该返回T | undefined所有未知索引访问的选项。


您可以实现自己的last并且输入更准确:

function last<T>(array: T[]): T | undefined // Explicit type
{
    return array[array.length - 1];
}
Run Code Online (Sandbox Code Playgroud)


And*_*man 3

我能想到的最佳解决方案是使用lodash 中的 last并将其添加为单独的包。我还通过安装单独添加了类型定义@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) 
Run Code Online (Sandbox Code Playgroud)