Generating and setting an object property in TypeScript at runtime

In my code, I have defined an interface as follows:

export interface OurHistory {
  ourHistory?: object;
  step1?:object;
  step2?:object;
}

Within the HistoryComponent class, I am doing the following:

export class HistoryComponent implements OnInit, OnDestroy {
  myHistory:OurHistory;

  let ourHistory = [];
  ourHistory = this.allHistory.fields['ourHistory'];
  this.myHistory.ourHistory = ourHistory[0];
}

However, I encounter an error message that says "Cannot set property 'ourHistory' of undefined"

Answer №1

The reason for this issue is due to the fact that on the second-to-last line in your code, this.myHistory is actually undefined. Essentially, you are attempting to access the property ourHistory of an object that does not exist according to the compiler.

To resolve this problem, it's necessary to initialize the property as stated in the comments attached to your question.

One possible solution is to modify your code like this:

export class HistoryComponent implements OnInit, OnDestroy {
  myHistory: OurHistory;

  let ourHistory = [];
  ourHistory = this.allHistory.fields['ourHistory'];
  this.myHistory = {ourHistory: ourHistory[0]};
}

By implementing this change, we create a new instance for the property myHistory:

{
   ourHistory: someValue
}

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

Exploring the world of Typescript, mastering tests, and diving deep into debugging

As a newcomer to Angular 2 and TypeScript, I recently created a basic application using the Angular CLI. However, I've encountered a gap in my understanding regarding how TypeScript code in VS Code translates into a functional app in a web browser. I ...

Creating a Session Timeout feature for Ionic/Angular that includes resetting the timer with each new user interaction

Having trouble implementing a session timeout feature in my code. I need the timer to reset whenever a user interacts with the function. Can't figure out how to integrate similar code like the one provided as an example on Stack Overflow. This is the ...

Having trouble transferring data from AppComponent to a function

When I send the email data to this.user in the constructor, it gets stored in AppComponent. Next, I need this variable in the function getUserData to import some data...but the console.log shows undefined, and there is also an error for users: Cannot read ...

Click on the div in Ionic 2 to send a variable

<div class="copkutusu" (click)="kanalsil(kanalid,deneme)" #kanalid id={{ver.channelid}} #deneme id={{ver.channelapikey}}></div> I am requesting kanalid.id and deneme.id in my .ts file. Even though they are the same variable names, they repres ...

Issues with navigation in React Native Typescript

Currently, I am in the process of developing a new React Native Expo project utilizing TypeScript. I have been attempting to configure navigation following the guidance provided in React Native's TypeScript documentation. However, upon running and sim ...

Angular offers a simple solution for adding events to all "p", "span", and "h1" elements easily

I am attempting to implement a "double click" event on all text HTML elements (p, span, h1, h2, etc.) across all pages in order to open a popup. I believe there should be a more efficient way than adding (dblclick)="function()" to each individual element. ...

Downloading Excel files in Angular using File Saver

Previously, I had set up a PHP post form that would download an excel file upon clicking the button. The form data was also posted to the URL successfully using plain HTML and submit form. This is the function in PHP that gets triggered when the form is p ...

Experiencing difficulty retrieving individual :id information from a list in MEAN stack

**I'm experiencing issues retrieving a single :id from a list as the data returned is not what I expected... ** GET /article/5b0be8829f734a4e580a43c5 401 3.845 ms - 99 ===> response from my get request my api ===> var express = require ...

Challenges in Angular 2

After building an application using Angular 2 with Lite Server, I noticed that it initially runs smoothly and quickly. However, over time, the performance starts to degrade and my application becomes sluggish. To address this issue, I typically restart L ...

A step-by-step guide for updating a minor version of Angular with Angular CLI

I've been searching online for the answer to this straightforward question, but can't seem to find it anywhere... In my angular 4 project (made with angular cli), I want to utilize the newly introduced http interceptors in version 4.3. Could so ...

Encountering a 401 error in Ionic 2 when making a post request to the WP-REST API, even though

I'm currently working on a simple application to manage posts in Wordpress using the wp-rest api. Everything, including creating, updating, and deleting posts, works perfectly fine when tested in Postman. I am also able to fetch posts successfully usi ...

extracting the HTML content from JavaScript and saving it into a standalone file

update When I click a link, a popup opens and I see all this HTML. The smile method is called when I click the link, and we append HTML in that method so that we can see it when the popup is opened. I moved it to a separate file something.component.html, ...

Navigating back to previous pages in an Angular(6) project connected to a Firebase Firestore database is a common requirement for

While there is an abundance of resources on how to paginate to the next page when using Angular with Cloud Firestore (Firebase), I have been unable to find a solution for pagination to a previous page. The closest I have come is returning to the first page ...

My NPM Install is throwing multiple errors (error number 1). What steps can be taken to troubleshoot and

I'm encountering an issue with my Angular project while trying to run npm install from the package.json file. Here are some details: Node version - 12.13.0 Angular CLI - 7.2.4 gyp ERR! configure error gyp ERR! stack Error: unable to verify the fi ...

Error message displayed in console due to AJV JSON schema validation when the maximum character limit is exceeded

In this provided example: { "default": "adsds", "max": 1 } I attempted to reference the dynamically provided 'max' value and validate the number of characters entered in the 'default' field. To achieve ...

Arrange photos in a grid using React Dropzone uploaders

I'm having trouble figuring out how to create a custom preview similar to an image set in a grid using the react-dropzone-uploader component for uploading multiple files. Currently, when I upload images, they are displayed as shown in my normal uploa ...

Encountering an ng build error while attempting to include a factory in the providers array

Currently, I am working on a school project where I implemented a basic HttpFactory and included it in the provider section of app.module.ts. However, upon running ng build, I encountered the following error: ERROR in Cannot read property 'provide& ...

How can you navigate to a particular page within a Single Page Application using NodeNS?

My NodeJS server is hosting a single page application that was built using Angular5. In certain circumstances, I need to direct users to a specific page within the application. For instance, during a designated time period, I want users to be redirected t ...

The declaration file for the 'react' module could not be located

I was exploring Microsoft's guide on TypeScript combined with React and Redux. After executing the command: npm install -S redux react-redux @types/react-redux I encountered an error when running npm run start: Type error: Could not find a decla ...

using props as arguments for graphql mutation in react applications

Here is the structure of my code: interface MutationProps{ username: any, Mutation: any } const UseCustomMutation: React.FC<MutationProps> = (props: MutationProps) => { const [myFunction, {data, error}] = useMutation(props.Mutati ...