0

When I try accessing a variable in an array using array assignment or lookup I get a typescript linting error saying that Object is possibly 'undefined'.ts(2532). I try checking that all of the variables in the operation are not undefined yet that does not work. Here is my current code which creates a clone of a 2d array and sets a specific value to true.

let start: [number, number] = [0,0];

const visited: boolean[][] = Array.from<boolean[], boolean[]>({ length: rows }, 
                        () => Array<boolean>(cols).fill(false));

      
visited[start[0]][start[1]] = true;

The error specifically underlines "visited[start[0]]". Furthermore, this error occurs when I access an array defined in my react state.

Rithwik Babu
  • 104
  • 1
  • 6
  • 2
    please use `visited[start[0]]?.[start[1]] = true;` – Pluto Jul 20 '23 at 04:57
  • TypeScript cannot guarantee that the indices `start[0]` and `start[1]` are valid, it warns you about the possibility of accessing an undefined element. To resolve this, You can use the optional chaining operator (`?`) to handle potential undefined values. – Debug Diva Jul 20 '23 at 07:35
  • 1
    The optional chaining operator does not work with assignment – Anton Jul 20 '23 at 10:04

1 Answers1

1

This behavior is controlled with compiler flag noUncheckedIndexedAccess. You seem to have this turned on (which I think is good). But that means that any time you access a value in an array, TypeScript will tell you that the element might be undefined, since TypeScript never knows the length of an array.

If you simply wish to access the value, you should use the optional chaining operator as suggested in the comments, visited[start[0]]?.[start[1]], it will give you undefined if visited[start[0]] doesn't exist.

However if you wish to assign a value, you can't use that approach (contrary to what the comments say) since it would possibly end up in the statement undefined = true which is invalid. I'd use the following approach, where we ensure Typescript that row actually exist.

const row = visited[start[0]]
if (row) {
  row[start[1]] = true
}

This might seem cumbersome but it's for the greater good (of type safety). If you however want the simple approach, just disable noUncheckedIndexedAccess and your original code will work.

Anton
  • 1,045
  • 1
  • 7
  • 16