What is the best way to handle accessing elements by index in an array in Typescript when the array can be empty, resulting in potentially undefined elements?
I am developing a simple game using React and Typescript where I have a variable named game
which holds an array of sets of type ISet
. In this scenario, each ISet
has a score
property that I need to access.
const game: ISet[] = [];
const currentSet = game[game.length - 1]; // The 'currentSet' variable will be of type 'ISet', but could be 'undefined' at this point
console.log(currentSet.score); // There won't be a Typescript error here, but running this code will result in a 'Uncaught TypeError: Cannot read property 'score' of undefined' error
How can I make Typescript aware that currentSet
might be undefined
in this situation?
I attempted to explicitly set the type of currentSet
like this:
const currentSet: ISet | undefined = game[game.length - 1];
However, this approach did not solve the problem. Changing the type declaration of game
to include undefined
like this:
const game: Array<ISet | undefined> = [];
Allows undefined
to be added to the array, which is not my intention and may lead to issues later on.
I have looked into various Github issues, such as this one, but have not found any suitable solutions. Using libraries like Underscore's last method could work, but it seems excessive to add a new package just to address this issue.
I appreciate any assistance or suggestions!
Andreas