Another TypeScript Novice Encounters the Error: TypeError - Trying to Assign Value to Undefined Property '3'

There seems to be an issue with the creation of the transitions Array, but I can't figure out why!

The text class

export enum STATE_ID { CGU, Initial, Previous, Question}
export enum CHOICE_ID {CGU_accepted, CGU_not_accepted}

export class STATE_MACHINE {
    constructor (context: string) {
    this.transitions_initialize()
}   
put_transition (source: STATE_ID, target: STATE_ID, label: CHOICE_ID): void 
{console.log(this.transitions.length.toString)
    this.transitions[source][label] = target
}
private transitions: STATE_ID[][] = new Array()
private transitions_initialize(): void {
    this.put_transition(STATE_ID.Initial, STATE_ID.Question,                                            
                                                     CHOICE_ID.CGU_accepted)
    this.put_transition(STATE_ID.Initial, STATE_ID.CGU,           
                                                 CHOICE_ID.CGU_not_accepted)
    }
}
new STATE_MACHINE("test")

The error

[Function: toString]
Z:\Documents\Phi\Developpement\TypeScript\test3\state_machine.js:45
    this.transitions[source][label] = target;
                                    ^
TypeError: Cannot set property '3' of undefined
    at STATE_MACHINE.put_transition (Z:\Docum................

Any thoughts on what might be causing this?

Answer №1

If you're looking to work with a multidimensional array in TypeScript or JavaScript, one key step is initializing each element properly beforehand. Here's an example:

private grid: CELL_VALUE[][] = new Array()

In this snippet, we've essentially created an empty array called grid. It doesn't contain any elements yet. Each element within it should be of type CELL_VALUE[]. To ensure that these elements exist when needed, you must instantiate them first. For instance:

set_cell_value(row: number, column: number, value: CELL_VALUE): void {
  if (!this.grid[row]) {
    this.grid[row] = new Array()
  }
  this.grid[row][column] = value
}

This method is intended to address any issues caused by uninitialized elements.

I hope this explanation proves useful to you. Best of luck with your coding!

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

An array becomes undefined once the previous array is removed

Consider the following code snippet: using the splice method, a specific item from Array1 is retrieved and stored in a variable called Popped. Next, Popped is added to array2. However, if we then delete the value from Popped, why does array2 become undef ...

What is the best way to locate the complement of an array?

When dealing with a sorted array of numerical values like Double, Integer, and Time, what is the typical approach to finding a complement? Throughout my time studying Computer Science in college, I have become more adept at grasping complements and handli ...

Is it possible for Visual Studio Code to create type declarations?

One of my tricks for quickly obtaining typings involves deriving them from actual data: https://i.stack.imgur.com/EPtMm.png I typically use a snippet like this: const ParcelFeatureTypeInstance = {"displayFieldName":"NAMECO","fieldAliases":{"PIN":"PIN / ...

Grouping Columns in an HTML Table using Angular 4

I'm currently faced with the task of retrieving flat data from an API and presenting it in an HTML table using Angular 4. I'm a bit unsure about how to iterate over the data, possibly using a for-each loop. I have attempted to utilize ngFor but I ...

Automatically assign the "Restricted" cursor to disabled fields within a dynamic form

Is there a method in Angular 6/7 that allows the cursor to change to "Not Allowed" when hovering over a disabled field in a reactive form? I prefer not to use CSS for this cursor change. Is there a way to achieve this through Angular alone? Currently, th ...

Error: An unexpected identifier was found within the public players code, causing a SyntaxError

As a newcomer to jasmine and test cases, I am endeavoring to create test cases for my JavaScript code in fiddle. However, I'm encountering an error: Uncaught SyntaxError: Unexpected identifier Could you guide me on how to rectify this issue? Below is ...

Angular: detecting mobile status within template

Often in my templates, I find myself repeating this type of code: <custom-button [align]="isMobile() ? 'center' : 'left'"></custom-button> This also requires me to include a method in each component to determine w ...

Refresh your content with the pull-to-refresh feature in Ionic 2

latest-news.html update function <ion-refresher (ionRefresh)="doUpdate($event)"> <ion-refresher-content pullingText="pull to update"> </ion-refresher-content> </ion-refresher> retrieve latest news from server <ion-li ...

The function signature '() => void' cannot be assigned to a variable of type 'string'

Encountering an issue in Typescript where I am attempting to comprehend the declaration of src={close} inside ItemProps{}. The error message received reads: Type '() => void' is not assignable to type 'string'. Regrettably, I am ...

Issue: Incorrect hook usage. Hooks are designed to be used within the body of a function component. This error may occur due to one of the following reasons: 1

I've reviewed similar questions and attempted to apply the solutions provided, but it seems I'm missing something specific to my situation. My goal is to streamline my code by importing headers from a utils file and using them across different AP ...

Creating dynamic key objects in TypeScript with index signatures: A beginner's guide

How can the code be optimized to automatically initialize a new product type without adding extra lines of code? Failure to initialize the variable results in a syntax error. enum ProductType { PC = 'pc', LAPTOP = 'laptop', TV ...

What is the reason for the selective use of the ampersand operator in C++ when assigning a pointer?

Why does assigning an array's memory address to a pointer differ from assigning a 'normal' variable's to a pointer? For example, int a; int* p = &a; I understand that using the ampersand in front of the array (&arr) points to its memor ...

Is there a way to access the filtered or organized rows in the Quasar Q-Table?

I have encountered a roadblock in my project. Despite installing Quasar version 2.0.0, I realized that it lacks a property to access the filtered or sorted rows. Previous versions of q-table had a computedRows property which was missing in the latest ver ...

I keep encountering an issue with a TypeError that says I am unable to read properties of undefined, specifically 'nativeElement'. Can anyone provide guidance on resolving this error

Here is the current state of my code: <mat-tree-node> ... <div *ngIf="node.type=='assembly' || node.type=='part'" style="display: inline;" (contextmenu)="asmStateServ.contextMenu($e ...

Use PHP regular expressions to search through arrays and calculate the sum of the last numbers

Recently, I received a file with a structure similar to this: 12345 ABC 100M 001 2.0 ABC 1010 4510 A01 451 Apple, Johnny A 150 12345 ABC 100M 011 2.0 ABC 1010 4510 A01 451 Apple, Johnny A 80 12345 ABC 100 011 2.0 ABC ...

Module logo.svg not found? Error in Typescript

Integrating package: vue-svg-loader. Established the file svg.d.ts with the content below: declare module '*.svg' { const content: any export default content } Utilizing it in a component in the following manner: import register from &apo ...

Tips for creating a single handler for an array of inputs in React

I've been able to create multiple handlers for various input fields, but I'm struggling with creating a single handler that can work for any number of dynamically generated input fields. Unfortunately, the inputs have fixed values and cannot be m ...

Discover how to validate a property within an array of objects and add the accurate values to a fresh array using TypeScript

I have a list of objects and I want to create a new array that contains only the objects with the 'read' property set to true. I've tried a couple of different methods, but I keep getting an error: Uncaught TypeError: Cannot read properties ...

Angular: Updating image tag to display asynchronous data

Utilizing Angular to retrieve user profile pictures from the backend, specifically Node.js/Express, has been mostly successful. However, there is one issue that I have encountered. The HTML displaying the profile picture does not re-render when the user up ...

Vue 3 - Child Component Script Not Updating with Reactive Prop Changes

I am facing an issue where I am trying to pass a reactive data as a prop to a child component in Vue 3. The data updates correctly in the child component's template, but it does not reflect in the child component's script. In the parent component ...