An error message stating 'Cannot read the name property of undefined' is being displayed, despite it being expected to be defined

interface InputField {
  readonly label : string;
  readonly data : string;
  readonly displayInline ?: boolean;
}

class FormField implements InputField {
  readonly label : string;
  readonly data : string;
  readonly displayInline ?: boolean;

  constructor(info : InputField) {
    this.label = info.label;
    this.data = info.data;
    this.displayInline = info.displayInline;
  }
}

When attempting to create a new instance of the FormField class within another class like so,

class FormSection implements Section {
  ...

  constructor(info : SectionInfo) {
    ...

    this.fields = info.fieldData.map((field) => new FormField(field));

    ...
  }
}

An error occurs with the message,

        this.label = info.label;
                          ^

TypeError: Cannot read property 'label' of undefined

If I print the value of info inside the constructor(...) method for FormField, it shows the object correctly (with altered values for privacy),

{
  data: '...information...',
  label: '...description...',
  displayInline: false
}

However, the error persists. The input provided to the FormSection constructor is extracted from a JSON object via a websocket, which is also true for the FormField constructor.

Answer №1

After some research, I found a helpful solution in this thread.

class Field implements IField {
  readonly name : string;
  readonly value : string;
  readonly inline ?: boolean;

  constructor(data : Partial<Field> = {}) {
    Object.assign(this, data);
  }
}

I made an adjustment by changing the data: any part to data: Partial<Field> = {}, setting a default value for the field. Credits to Wiktor for guiding me in the right path.

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

React error: The module "react-router-dom" does not have a member named "useNavigate" available for export

I'm attempting to include useNavigate for use as outlined in the top answer here: react button onClick redirect page import { useNavigate } from "react-router-dom"; However, I am encountering this error: export 'useNavigate' (impo ...

Enforcing TypeScript restrictions on method chaining during object creation

Let's consider this unique sample class: class Unique { public one(): Pick<this, "two" | "three"> { return this; } public two(): Pick<this, "three"> { return this; } public three(): string { ...

What is the best way to implement a timer using hooks in React?

Just getting started with React! I began my journey last week ;) My first task is to build a timer that includes a reset feature and can count seconds. While the reset function is functioning properly, the timer isn't. Can anyone suggest the best ap ...

What is the proper way to expand a TypeScript class?

I'm facing a dilemma with the code snippet below. The line m.removeChild(m.childNodes[0]) is causing an issue with the TypeScript compiler. I'm unsure if childNodes: BaseNode[]; is the correct approach in this scenario. class BaseNode { childNo ...

Invoke a component's function in a different component

Upon clicking the button, I am trying to execute the 'exportHistoryToCSV' method within this component, which in turn calls a method from another component. However, I am encountering an error. @UntilDestroy() @Component({ selector: 'd ...

What is the reason behind a TypeScript compiler error being triggered by an 'if-else' statement, while a ternary operator construct that appears identical does not raise any errors?

My function is designed to either return a value of IDBValidKey or something that has been converted to IDBValidKey. When I use the ternary operator to write the function, it works fine. However, if I try to write it as an if-else statement, it causes a co ...

What is the best way to change an array element into a string in TypeScript?

Within my Angular 2 component, I am utilizing an array named fieldlist which is populated by data retrieved from an http.get request. The array is declared as follows: fieldlist: string[] = []; I populate this array by iterating through the JSON response ...

Creating a TypeScript type based on the static values of a class

In my Market class, there is only one parameter: name. class Market { name: string constructor(name: string) { this.name = name } } Next, I have a Markets class that contains a static collection of multiple markets. class Markets { static M1 ...

When you type a letter in the middle of a string, the cursor is automatically moved back to the end - Material UI

I designed a ChipInput feature that switches to a string when focused and transforms into a Chip component when blurred, with chips separated by commas. Everything seems to be functioning properly except for one issue I am encountering. Whenever I type in ...

What is the best way to distribute a Typescript module across multiple projects without having to duplicate it each time?

I currently have two folders named shared and project1 within a larger folder called node. I am in the process of working on multiple Node projects that are independent and are all located within the node folder. Within the shared folder, there is an inde ...

Error: The variable __WEBPACK_EXTERNAL_MODULE_XX__ has not been defined

A unique npm package called our-map has been developed utilizing TypeScript, webpack, and the ArcGIS JS API to encapsulate an esri map within a React component. The functionality of the module has been verified through testing on a dedicated page within th ...

Switching class on a specific element in Angular 2

My element list appears like this: <ul *ngFor="let period of periodsDate"> <li [class.show]="isShown" (click)="toggleClass()"> <a>{{ period.id }} </a> </li> </ul> ...

Tips for showing various tooltip text when iterating through a list?

I am currently working on a project where I am looping through a list and attempting to assign different tooltip text to various icons. However, I am struggling with the implementation. Here is a snippet of my code: <React.Fragment key={sv.key ...

What are the recommended TypeScript tsconfig configurations for running Node.js 10?

Can someone provide information on the necessary target/libs for enabling Node.js v10.x to utilize async/await without generators? I have found plenty of resources for node 8 but not as much for node 10. ...

Invoking a subclass method's constructor using a generic parameter

The code below is not passing the type-checking: type MyFunctionConstructor<T, F extends MyFunction<T>> = new ( f: (n: number) => T ) => F; class MyFunction<T> { constructor(f: (n: number) => T) { this.f = f; } f: ...

The guide to integrating the npm package 'mysql-import' into a node.js project with TypeScript

I'm currently facing an issue while trying to import a dump to a database using node.js and the npm module 'mysql-import'. Initially, I wrote the code in JavaScript and it worked flawlessly. However, when I attempted to modify it for TypeScr ...

What is the best way to shorten text in Angular?

I am looking to display smaller text on my website. I have considered creating a custom pipe to truncate strings, but in my situation it's not applicable. Here's what I'm dealing with: <p [innerHTML]="aboutUs"></p> Due to t ...

The Problem of Unspecified Return Type in Vue 3 Functions Using Typescript

Here is the code snippet I am working with: <template> <div> <ul v-if="list.length !== 0"> {{ list }} </ul> </div> </template> < ...

Determine the type of the final function within a variable number of nested closures

Imagine you have a function like this: const f = a => b => ... x => { return somevalue } Is there a way to determine the type of just the final function typeof x => { return somevalue } even if we don't know how many closures come before ...

Having completed "npm link" and "npm i <repo>", the module cannot be resolved despite the presence of "main" and "types" in the package.json file

Here is the contents of my package.json file: { "name": "ts-logger", "main": "dist/index.js", "types": "dist/index.d.ts", "scripts": { "install": "tsc" ...