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
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];
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With