Encountering an undefined value despite having declared the variable in TypeScript

In my Angular application, I am encountering an issue while trying to add values to an array within a block of code.

Even though I have defined the variable 'contactWithInitials', I keep receiving an error message stating 'Cannot read property push of undefined'.

What could be causing this problem?

    let initialHold: any;
    let contactWithInitials: any [];

    this.contacts.forEach( eachObj => {
      if(eachObj.first_name){
        initialHold = eachObj.first_name.charAt(0);
      }
      if(eachObj.last_name){
        initialHold += eachObj.last_name.charAt(0);
      }

      contactWithInitials.push({'userInitials':initialHold});

    })

Answer №1

You have defined the type contactWithInitials, however you have not initialized it...

let contactWithInitials: any[] = [];

// Alternatively, if you prefer a more specific type
let contactWithInitials: { 'userInitials': string }[] = []

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

Partial argument cannot be assigned to the specified parameter type

I'm attempting to update a partial property of an interface in TypeScript like this: interface details{ name: string, phonenumber: number, IsActive: boolean } let pDt: Partial<details> = {IsActive: false}; However, when I try to pass it ...

Ways to parse the data from a response received from an Axios POST request

After sending the same POST request using a cURL command, the response I receive is: {"allowed":[],"error":null} However, when I incorporate the POST request in my code and print it using either console.log("response: ", resp ...

Decoding enum interface attribute from response object in Angular 4 using typescript

From an API response, I am receiving an enum value represented as a string. This enum value is part of a typescript interface. Issue: Upon receiving the response, the TypeScript interface stores the value as a string, making it unusable directly as an en ...

Issue with React not displaying JSX when onClick Button is triggered

I've recently started learning React and I'm facing a problem that I can't seem to figure out. I have a basic button, and when it's clicked, I want to add another text or HTML element. While the console log statement is working fine, th ...

What is the best method to integrate my custom Angular Single Page App instead of a webpage using Greasemonkey?

How can I use Greasemonkey to replace the HTML code of a website with my own Angular Single Page App? Motivation: I have come across an old website that is in need of a redesign, but the owner seems uninterested. I want to create an Angular SPA that will ...

Has the antd Form.create() method been substituted with something else?

I have been working on creating a login page in react using antd. I came across a tutorial that seems to be outdated as it is giving me an error. After researching on a forum, I found out that form.create() is no longer available, but I am unsure of how to ...

Combining HTTPHandler Observable with another in HTTPInterceptor (Angular 8)

In our Angular 8 project, we have set up our API so that the response includes both a "data" attribute and an "errors" attribute. It's possible for there to be data as well as errors in the response, and we need access to both in the calling component ...

Unable to access the camera page following the installation of the camera plugin

The issue I'm encountering involves using the native camera with the capacitor camera plugin. After implementation, I am unable to open the page anymore - clicking the button that should route me to that page does nothing. I suspect the error lies wit ...

When I try to install dependencies with Hardhat, the "Typechain" folder does not appear in the directory

After installing all the dependencies, I noticed that the "typechain" folder was missing in the typescript hardhat. How can I retrieve it? Try running npm init Then, do npm install --save-dev hardhat Next, run npx hardaht You should see an option to se ...

Issues with ngClass in AngularAngular's ngClass feature is failing

In my ngClass condition, it looks like this: <div [ngClass]="{'alert alert-danger': alert.type == 0,'alert alert-success': alert.type == 1}" When alert.type == 1, the class is set to alert alert-success. But when alert.type = 0, th ...

Creating a CSS class in a separate file for an element in Angular 4

Looking for some help with my code setup. Here's what I have: <div class="over"> Content </div> In my component file, this is what it looks like: @Component({ selector: 'app', templateUrl: './app.componen ...

Guide on successfully importing a pretrained model in Angular using TensorFlow.js

I need help with uploading a pretrained Keras model to my existing tensorflow.js model and then making simple predictions by passing tensors in the correct format. The model is stored locally within the project, in the assets folder. export class MotionAn ...

Running Protractor tests with 'directConnect: true' causes the ERROR:browser_switcher_service.cc(238)] XXX Init() to be thrown

While running Protractor tests with directConnect: true, I am encountering an error as soon as the browser window appears. Interestingly, the test continues to run smoothly without any apparent issues. However, when I switch to Firefox or use seleniumAddr ...

The reason behind the clickable issue with my duplicate <ion-select>

I've been working on a form using HTML, CSS, and JavaScript where I implemented an "Add" button to duplicate the form. The issue arises with the ion-select element within the duplicated form. While the original form displays all predefined options upo ...

"Combining the power of AngularJS2 beta with Spring Boot: the ultimate

I am currently using Atom 1.4.0 with the atom-typescript package to develop AngularJS2 modules in TypeScript. On the backend, I have a spring-boot application for handling the REST APIs. After making changes to the .ts files in Atom, it seems to compile t ...

Troubleshooting Angular directives and the complications of closures

I am facing a problem with this specific directive: @Directive({ selector: '[imgTest]', }) export class ImgTest implements AfterViewInit, OnDestroy { private originalImage: HTMLImageElement; private secondImage: HTMLDivElement; construc ...

Utilizing nested objects in ngrx/store effects

Currently, I am in the process of learning Angular 2 and experimenting with ngrx/store. However, I am encountering some challenges when it comes to dealing with certain special cases. For instance, one issue I am facing is attempting to remove a parent ob ...

Incorporated iframe covering the entire browser window

Currently, I find myself in a strange predicament. The scenario involves a JSP+Servlet+Spring MVC application that is integrated within a parent application developed using Angular4 through an iframe. The issue arises when the Spring MVC app redirects to ...

What is the best way to extract children of a specific type by filtering through their parent type in TypeScript?

What I'm looking for In a key-value parent object, I have multiple objects with a property called namespaced of type boolean: const obj1 = { namespaced: true, a() {} } as const const obj2 = { namespaced: false, b() {} } as const const pare ...

Trouble encountered while using useRef in TypeScript

I'm encountering an issue with the code below; App.tsx export default function App() { const [canvasRef, canvasWidth, canvasHeight] = useCanvas(); return ( <div> <canvas ref={canvasRef} /> </div> ) ...