Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle potential empty array when accessing by index in Typescript

What's the preferred way to access elements by index in an array in Typescript when the array also can be empty, leading to elements being undefined?

I'm coding a simple game in React with Typescript where I have a game variable consisting of an array of sets of type ISet. In this simplified example, ISet has a score property in it's interface, which I try to access

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

How can I have Typescript detect currentSet potentially being undefined here?

I've tried to manually set currentSet's type to

const currentSet: ISet | undefined = game[game.length - 1];

but that doesn't work, and changing the type declaration to

const game: Array<ISet | undefined> = [];

allows undefined to be added to the array, which is not what I'm after and will lead to problems later on.

I've read through a couple of GitHub issues, like this one, but couldn't find any suggestions on workarounds. Using something like last from Underscore would work, but it seems a bit overkill to a new package to bypass this issue.

Looking forward to some help!

Andreas

like image 732
Andreas Näsman Avatar asked May 21 '26 06:05

Andreas Näsman


1 Answers

TypeScript > v4.1 has the option noUncheckedIndexedAccess which should return T | undefined for all unknown index access.


You could implement your own last and be more accurate in its typing:

function last<T>(array: T[]): T | undefined // Explicit type
{
    return array[array.length - 1];
}
like image 99
H.B. Avatar answered May 26 '26 19:05

H.B.