Encountering the error message "Attempting to access a null or undefined value while populating an array within a loop in TypeScript."

I am relatively new to TypeScript and currently working on one of my initial projects in Microsoft Makecode Arcade. I am attempting to populate an array as a class property using a 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)
        }
    }
}

An error message is displayed stating "Dereferencing null/undefined value", even though console.log(row) displays the correct array [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

Answer №1

You forgot to initialize the grid array in your code snippet (check out the 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)
        }
    }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The type 'Handles' does not contain the properties present in type 'TextInput'

Implementing a phone number field using React Native Paper and react-native-text-input-mask: // Necessary Imports import {TextInput} from 'react-native-paper' import TextInputMask from 'react-native-text-input-mask' // Control Implemen ...

Creating a declaration file for a library's entry point involves outlining the structure and types

I have developed an npm library that is made up of several ES6 modules, which are then consolidated into a single js file. The directory structure looks like this: src main.ts one.ts two.ts three.ts types index.d.ts index.ts The index.ts fil ...

What led the Typescript Team to decide against making === the default option?

Given that Typescript is known for its type safety, it can seem odd that the == operator still exists. Is there a specific rationale behind this decision? ...

Unable to view the refreshed DOM within the specifications after it has been altered

For my current project, I am working on writing a functional spec that involves using Mocha/JSDOM and making assertions with 'chai'. The specific use case I am tackling is related to the function called updateContent: When this function is exec ...

In React Native, you can pass native component properties as props, while also defining custom ones using a TypeScript interface

I am working on a component called AppText where I need to utilize a Props interface and also be able to accept additional props that can be spread using the spread operator. However, I encountered this error: Type '{ children: string; accessible: tru ...

A TypeScript interface that corresponds to a function and its input parameters

I have multiple functions with various argument types: function foo(a: number) {...} function bar(a: string) {...} ... To tackle this, I want to define a TypeScript interface (or type) that can handle these scenarios: interface MyInterface { method: ty ...

Supporting right-to-left (RTL) localization in Angular 2 and later versions

When it comes to incorporating right-to-left (RTL) support into a localized Angular 2+ application, particularly for languages like Hebrew and Arabic, what is considered the best approach? I have explored various tutorials, including Internationalization ...

The 'string' Type in Typescript cannot be assigned to the specified type

Within the fruit.ts file, I've defined a custom type called Fruit which includes options like "Orange", "Apple", and "Banana" export type Fruit = "Orange" | "Apple" | "Banana" Now, in another TypeScript file, I am importing fruit.ts and trying to as ...

Incorporating a complex React (Typescript) component into an HTML page: A Step-by

I used to have an old website that was originally built with Vanilia Javascript. Now, I am in the process of converting it to React and encountering some issues. I am trying to render a compound React(Typescript) component on an HTML page, but unfortunatel ...

Is there a way to refactor the onAuthStateChanged function from useEffect in firebase to a class component?

Below is the code snippet used in the function component: useEffect(() => { const unsubscribe = firebase.auth().onAuthStateChanged(user => { setIsLoggedIn(!!user); }); return () => { unsubscribe(); }; }); And here is ...

Errors in Intellisense detected within the latest Node Tools Express App development project

After setting up a new project with the "Basic Node.js Express 4 Application" template, I noticed some errors have already surfaced: https://i.sstatic.net/8jbYt.png Could this be a Visual Studio issue? Any pointers on resolving these errors? ...

Error in Typescript: Function not being triggered on button click

As someone who is just starting out with typescript, I've been tackling a simple code that should display an alert message in the browser when a button is clicked. I've experimented with the button and input tags, as well as using both onclick ev ...

What causes an array of type `never[] & number[]` to be generated when using `Object.assign`?

Take a look at this code snippet: const arr = [1,2,3] const res1 = arr.slice() const res2 = Object.assign([],arr) When using arr.slice() to create a shallow clone, the resulting array res1 will have a type of number[], just like the original arr. However, ...

What is the solution to fixing a 400 bad request error in Angular Routing?

Encountering an issue on a particular route where a 400 error is displayed in the screenshot every now and then. It seems to work fine for a few minutes after deleting cookies, but the error resurfaces after accessing it multiple times. Other routes are fu ...

Avoid stopping Bootstrap Vue's events

Need help with a b-form-select control in Bootstrap Vue. Trying to execute a function when the value changes, but want the option to cancel the event and keep the original value. Complicating matters, the select is in a child component while the function ...

Conditional Skipping of Lines in Node Line Reader: A Step-by-Step Guide

I am currently in the process of developing a project that involves using a line reader to input credit card numbers into a validator and identifier. If I input 10 numbers from four different credit card companies, I want to filter out the numbers from thr ...

Using Angular Typescript, implement a live chat feature that generates link previews

I am having trouble creating a link preview in live chat on my website. I want the preview of a dropped URL to show in the chat window, which requires extracting meta-data from the element of the resource (in that URL) like: <meta property="og:imag ...

Guide to Automatically Updating Angular Component When Service Data Changes

I am currently working on an Angular application that features a sidebar component displaying different menu items based on the user's data. The sidebar should only display an option for "Empresas" if the user has not created any company yet. Once a c ...

Expanding the Warnings of React.Component

When I create a new class by extending React.Component in the following manner: export default class App extends React.Component<any, any > { constructor (props: React.ReactPropTypes) { super(props); } // other code } I encountere ...

How do I retype an interface from a dependency?

It's difficult to put into words, so I have created a repository for reference: https://github.com/galenyuan/how-to-retyping My goal is to achieve the following: import Vue from 'vue' declare module 'vuex/types/vue' { interfac ...