reactjsarraystypescriptlinter

Object is possibly 'undefined'. During typescript array assignment and lookup


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.


Solution

  • 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.