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 listMyClass : myClass[]; has been declared and it gets populated with data from an API during ngOnInit().

The Objective

The goal is to create a method in component.ts that will iterate through listMyClass and add items to a list of the people class if their city matches "london".

An attempt was made to write a method outside of ngOnInit():

getLondonPeople(){     
    for (let item in listMyClass) {
        if (item.city == "london") {
            //do something
        }
    }

    return listPeople;
}

The Issue

An error occurs on item.city with the message:

Property 'city' does not exist on type 'string'.

How can this be resolved?

Answer №1

Reason Behind the Error

This error occurs because when using for-in, you are not actually looping through the values you intend to. As explained in the official documentation:

Both for...in and for...of statements iterate over something, but they differ in what they actually iterate over.

The for...in statement loops through enumerable properties of an object in random order.

The for...of statement loops through values defined by the iterable object.

Solution for this Issue

To address this issue, it is recommended to use for-of instead of for-in. Here's how:

for (let item of listMyClass) ...

Alternatively, for better efficiency in obtaining specific items, consider utilizing filter instead of a traditional for-loop, like so:

this.listMyClass.filter(item => item.city === 'London')

Illustrative Example

I have created a simple example on Stackblitz to demonstrate the suggested solutions:

https://stackblitz.com/edit/unrecognized-property-example

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

Angular template error: 'Component' type does not have the specified property

I am facing an issue with importing an array from a file named platforms.ts. The array is declared as shown below: export const platforms: Platforms[] = [ { name: 'Instagram', value: 'instagram' }, { name: 'Facebo ...

Retrieving a nested type based on a particular condition while keeping track of its location

Given an object structure like the one below: type IObject = { id: string, path: string, children?: IObject[] } const tree = [ { id: 'obj1' as const, path: 'path1' as const, children: [ { id: &ap ...

The character 'T' cannot be assigned to the data type 'number'

When working with an optional type argument function RECT(T), I encountered a situation where I need to check if the argument is an instance of date. If it is, I convert it to a number; if not, I use the number directly. However, I keep getting an error ...

What could be causing the ExcelJs plugin to malfunction in Internet Explorer 11?

My current setup involves Angular 9 and excelJs 4.1.1, which works perfectly in Chrome but throws an error in IE11 stating: "Invalid range in character set" in polyfills-es5.js Surprisingly, when I remove this dependency from package.json, everything func ...

What is the process for accessing my PayPal Sandbox account?

I'm having trouble logging into my SandBox Account since they updated the menu. The old steps mentioned in this post Can't login to paypal sandbox no longer seem to work. Could someone please provide me with detailed, step-by-step instructions o ...

Encountering the issue "Unable to define properties of undefined" during Angular unit testing tasks

When attempting to write a unit test case for a dropdown, an error is encountered: TypeError: Cannot set properties of undefined (setting 'ReferralCodes') .spec.ts it("should update the action selecting a value from category drop down", ...

Tips for updating property values when calling a TypeScript function

Hello everyone, I am looking to convert a snippet of JavaScript code into TypeScript. JavaScript function newState(name){ var state ={ name : name, age : 0 } return state } function initStates() { this.JamesStat ...

Experimenting with TypeScript Single File Component to test vue3's computed properties

Currently, I am in the process of creating a test using vitest to validate a computed property within a vue3 component that is implemented with script setup. Let's consider a straightforward component: // simple.vue <script lang="ts" set ...

Icon for TypeScript absent from npm package listings

Recently, I created a package and uploaded it to the npm repository. The package was displayed with an icon labeled "ts" on the website. https://i.stack.imgur.com/LoY1x.png The accompanying package.json showcased the inclusion of the "ts" icon - https:// ...

How to Resolve File Paths in CSS Using Angular 7 CLI

My assets folder contains an image named toolbar-bg.svg, and I am attempting to use it as the background image for an element. When I use background: url('assets/toolbar-bg.svg'), the build fails because postcss is unable to resolve the file. How ...

Challenges arise when dealing with generics in TypeScript

I'm a beginner in TypeScript and I'm trying to write a method with a generic type argument similar to what you can do in .Net. Here's the code snippet I've been working on: class TestObject { Id: number; Truc: string; Machin: str ...

Angular Material's dialog modal swiftly closes without delay

Could you please explain why the modal opens and then closes instantly when I click on the Create Project button? https://example.com/edit/angular-code I am trying to display a component within the modal using Angular Material. portafolio.component.ts ...

How can I determine the existence of an S3 bucket and, if it doesn't exist, create it using TypeScript CDK?

I am currently facing an issue where I need to verify the existence of a bucket in the account and either create a new one if it doesn't exist or use the existing bucket My attempt at achieving this is as follows: import {Bucket} from 'aws-cdk-l ...

Issues with connecting to server through Angular websocket communication

I deployed the server on an Amazon AWS virtual machine with a public IP address of 3.14.250.84. I attempted to access it using Angular frontend like so: public establishWebSocketConnection(port : number){ this.webSocket = new WebSocket('ws://3.14.250. ...

Retrieve the dimensions of a child component when NgIf condition is met

I am facing a situation where I have a main component with a child component that is populated using NgFor. To control the visibility of the child, the parent sets a property called childIsVisible to false and binds it to the child using *ngIf="childIsVisi ...

The Angular-Chart.js chart fails to display when data is automatically inserted

I came across this sample code at https://stackblitz.com/edit/angular-chartjs-multiple-charts and tried using it. Everything was working well with static data, but when I attempted to push data retrieved from the Firebase Realtime Database into the chart, ...

Is a date-time picker not available for use in Angular version 17?

While delving into Angular 17 and Bootstrap 5, I came across a surprising issue where the code snippet below failed to save the date and time accurately: <input type="datetime-local"> On the other hand, the following code managed to save t ...

React slick slider not functioning properly with custom arrows

"I have encountered an issue while trying to implement multiple sliders in my component with custom arrows positioned below each carousel. Despite following the documentation meticulously, the arrows do not respond when clicked. What could possibly be ...

How can I send a value to an Angular element web component by clicking a button with JavaScript?

I want to update the value of an input in an Angular component by clicking on a button that is outside of the Angular Element. How can I achieve this in order to display the updated value in the UI? Sample HTML Code: <second-hello test="First Value"&g ...

Leverage TypeScript generics to link props with state in a React class-based component

Can the state type be determined based on the prop type that is passed in? type BarProps = { availableOptions: any[] } type BarState = { selectedOption: any } export default class Bar extends React.Component<BarProps, BarState> { ...