Issue with assigning objects to an array

I'm currently working on a TypeScript application and I've run into an issue with assigning values. Here are the interfaces for reference:

export interface SearchTexts {
    SearchText: SearchText[];
}

export interface SearchText {
    Value: string;
    BusinessID: string;
}

This is how you should assign the values:

let searchTextArr: SearchText[] = [];
const invoiceNumbers: string[] = ["INV4587965", "INV4589654"];

for (var index in invoiceNumbers) {
  let searchText: SearchText = {
    Value: invoiceNumbers[index],
    BusinessID: "BSD458"
  };    
  searchTextArr.push(searchText);
}

let searchItems: SearchTexts;
searchItems.SearchText = searchTextArr; //Encountering error during assignment

The error message is as follows:

(node:17661) UnhandledPromiseRejectionWarning: TypeError: Cannot set property 'SearchText' of undefined

I have used console.log to check if searchTextArr contains values, and it does. However, I am still unable to pinpoint the issue. If anyone can help me identify where the problem lies, I would greatly appreciate it.

Answer №1

It appears that you are attempting to retrieve data from an object named searchTexts, but it seems that this object has not been defined or initialized in your code. This is likely why you are encountering the error message:

cannot read SearchText of undefined

To resolve this issue, you can follow the suggestion provided by @ttquang1063750 and declare the variable as shown below:

const searchTexts: SearchTexts = {SearchText: []};

Be sure to place this declaration just outside of your for loop.

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

Having difficulty navigating to a different page in Angular 4

I'm currently attempting to transition from a home page (localhost.com) to another page (localhost.com/listing). Although the app compiles correctly, I encounter an issue where nothing changes when I try to navigate to the new page. My approach has m ...

No recommended imports provided for React Testing Library within the VS Code environment

I am currently in the process of setting up a Next JS project with Typescript integration and utilizing React Testing Library. Unfortunately, I'm facing an issue with getting the recommended imports to work properly within my VS Code environment. To i ...

Having trouble executing the project using Gulp

I'm a beginner in front-end development and I am working on an existing project that I'm having trouble running. According to the documentation, I should run the project by executing: $ gulp && gulp serve But I keep getting this error: ...

Modifying the State in a Class Component

private readonly maxSizeOfDownloadedFiles: number = 1000000; state = { totalSum: this.maxSizeOfDownloadedFiles }; handleCallback = () => { this.setState({ totalSum: 12 }) alert('totalSum ' + this.state.totalSum); }; Upon executing the ...

Encountering a Angular 12 Observable<Object[]> Error while attempting to execute a GET request

I've been grappling with this error I encountered while working on Angular 12. Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays. This is the code f ...

Data cannot be transferred to a child element unless it has been initialized during the definition phase

Passing an array data from parent to child component has brought up some interesting scenarios: parent.component.html: <child-component ... [options]="students" > </child-component> Status I: Setting the array on definition ...

`Next.js: Addressing synchronization issues between useMemo and useState`

const initializeProjects = useMemo(() => { const data: ProjectDraft[] = t('whiteLabel.projects', {returnObjects: true}) const modifiedData: ProjectWL[] = data.map((item, index) => { return { ... ...

In AngularJS, the use of the '+' operator is causing concatenation instead of addition

Looking for assistance with my TypeScript code where I've created a basic calculator. Everything is working as expected except for addition, which seems to be concatenating the numbers instead of adding them together. HTML CODE : <input type="tex ...

Angular 8 HTTP Interceptor causing issues with subscriptions

I'm currently in the process of setting up an Angular 8 project that will allow me to mock API calls using HTTP INTERCEPTORS. My approach involves adding a --configuration=mock flag to my ng serve script so that the interceptor is injected into my app ...

Error: Exceeded Maximum Re-Renders. React has set a limit on the number of renders to avoid infinite loops. Issue found in the Toggle Component of Next.js

I am struggling with setting a component to only display when the user wants to edit the content of an entry, and encountering an error mentioned in the title. To achieve this, I have utilized setState to manage a boolean using toggle and setToggle, then ...

Form with checkboxes in a Next.js and Typescript application

I am currently working on a project using Next.js and Typescript. I have implemented a form in this project, which is my first experience with Typescript and checkbox types. However, I am encountering difficulties in retrieving all checkbox values, adding ...

Utilizing getter and setter functions within a setter with a type guard

I need to implement a getter and setter in my class. The setter should accept a querySelector, while the getter is expected to return a new type called pageSections. The challenge I'm facing is that both the getter and setter must have the same argum ...

Potential Issue: TypeScript appears to have a bug involving the typing of overridden methods called by inherited methods

I recently came across a puzzling situation: class A { public method1(x: string | string[]): string | string[] { return this.method2(x); } protected method2(x: string | string[]): string | string[] { return x; } } class B extends A { prot ...

What is the process for upgrading TypeScript to the newest version using npm?

My current TypeScript version on my machine is 1.0.3.0 and I am looking to upgrade it to the latest version, which is 2.0. Could someone please guide me on how to accomplish this using npm? ...

Creating a personalized menu using Nextron (electron) - Step by step guide

I'm currently in the process of developing an app with Nextron (Electron with Nextjs and Typescript). Although I have the foundation of my Next app set up, I've been encountering issues when attempting to create a custom electron menu bar. Every ...

Error: Trying to modify an immutable property 'title' of object '#<Object>' - React JS and Typescript

Whenever I press the Add button, all input values are stored in a reducer. However, if I append any character to the existing value in the input fields, it triggers the following error: Cannot assign to read only property 'title' of object &apos ...

The name 'CallSite' is missing from the Error stack trace when working with Node.js and TypeScript

I am facing an issue with the following code: Error.prepareStackTrace = function ( error: Error, stack: Array<CallSite>, ) { return self.parse(fiber, error, stack) } I am attempting to import the CallSite, but it seems like it cannot be found ...

Do [(ngModel)] bindings strictly adhere to being strings?

Imagine a scenario where you have a radiobutton HTML element within an angular application, <div class="radio"> <label> <input type="radio" name="approvedeny" value="true" [(ngModel)]=_approvedOrDenied> Approve < ...

Angular Service singleton constructor being invoked multiple times

I have been facing an issue with using an app-wide service called UserService to store authenticated user details. The problem is that UserService is being instantiated per route rather than shared across routes. To address this, I decided to create a Core ...

What could be the reason for a property going unnoticed during the iteration of a list?

The Scenario There is a class named myClass: export class myClass { name: string; age: number; city: string; } and another class called people: export class people { name: string; age: number; } In the component.ts, a variable list ...