typescriptmakecode

Getting "Dereferencing null/undefined value." while trying to fill array in the loop in TypeScript


I'm quite new to TypeScript and this is one of my first projects in Microsoft Makecode Arcade. Trying to fill an array as a class property using loop.

class Game {
    grid: number[][]

    constructor() {
        for (let i = 0; i < 20; i++) {
            let row: number[] = []
            for (let j = 0; j < 10; j++) {
                row.push(0)
                console.log(row)
            }
            this.grid.push(row)
        }
    }
}

Getting an error "Dereferencing null/undefined value", however, console.log(row) shows the correct array [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]


Solution

  • You don't initialize grid (demo)

    class Game {
        grid: number[][]
    
        constructor() {
            this.grid = []
            for (let i = 0; i < 20; i++) {
                let row: number[] = []
                for (let j = 0; j < 10; j++) {
                    row.push(0)
                }
                this.grid.push(row)
            }
        }
    }