Exploring an array of custom objects in TypeScript with a loop

Recently, I decided to experiment a bit with TypeScript. I ended up creating two classes - Student and Listview. The goal was to loop over an array of student objects that I had created but for some reason, it's not working as expected.

class Student {
    fullName: string;
    constructor(public firstName, public middleInitial, public lastName) {
        this.fullName = firstName + " " + middleInitial + " " + lastName;
    }
}

class Listview {
    items: Array<Student>;
    constructor(public item_list: Array<Student>) {}

    log(): void {
        var items = this.items;
        for(var i=0; i<items.length; i++) {
          console.log(items[i]);
        }
    }

}

var list = new Listview(
    [new Student("Jane", "M.", "User"),
    new Student("Hans", "M.", "Muster"),
    new Student("Fritz", "B.", "Muster")]
);
list.log();

Upon checking the console, I noticed a warning message:

console error

I'm struggling to understand how to properly access the array in order to retrieve the properties of each student object. Any help or advice would be greatly appreciated.

Best regards, Orkun

Answer №1

To properly set up your ListView and initialize the items array, use the following code:

class CustomListView {
    constructor(public items: Array<Student>) {}

    displayItems(): void {
        var items = this.items;
        for(var index=0; index<items.length; index++) {
          console.log(items[index]);
        }
    }
}

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

Understanding how types intersect in TypeScript

I'm currently diving into Type Relations in TypeScript. Can someone help explain what happens when we intersect the types represented by these two expressions: {a:number}[] & {b:string}[] Does this result in {a:number, b:string}[] ? Any clarificat ...

Steps to deactivating a styled button using React's styled-components:

I've created a very basic styled-components button as follows: import styled from 'styled-components'; const StyledButton = styled.button``; export const Button = () => { return <StyledButton>Default label</StyledButton> ...

Looking for a TypeScript annotation that allows accessing an object property using a variable

When working with plain JavaScript, we have the ability to access an object's property value using a variable. For example, this is permitted: let obj = { a: 100, b: 'Need help with TypeScript', c: new Date() }; let prop = 'b'; c ...

Caution: Updating a component is not possible during the rendering of another component. ReactJS

I am encountering an error in my ReactHooks/Typescript application with a Navigation component that renders a PatientInfo component. The PatientInfo component is conditionally rendered based on the props it receives, determined by a searchbox in another ch ...

Is it possible to execute user-defined functions dynamically in a Node.js application without having to restart the server

I am exploring the potential for allowing users to insert their own code into a Node application that is running an express server. Here's the scenario: A user clicks 'save' on a form and wants to perform custom business validations. This ...

Is my C++ character array being corrupted?

I have been working on a function to streamline the sprintf function, but I have encountered a strange issue: Right after calling the class (which used to be a function without success), I am getting the expected output: However, the following line displ ...

Refreshing only a portion of the back-end using dynamic imports

Within my node backend, the file structure is as follows: project |-- expensive | |-- index.ts |-- files | |-- foo.ts | |-- bar.ts | `-- baz.ts |-- tsconfig.json |-- package.json `-- index.ts I am interested in reloading only a portion of my proje ...

Ways to shuffle an element within an array

I'm currently working on programming a version of Minesweeper and I'm looking for assistance with randomizing the placement of bombs in the game. Could someone help me modify the function so that the bomb placements are randomized? HERE IS THE ...

Check two arrays by comparing the first array and return the values that have a partial match, even if they are not

Hi there, I'm trying to filter my array based on another array, even if the values don't match exactly. Here is an example of what I'm working with: First array: [Mon Sep 09 2019 00:00:00 GMT+1000 (Australian Eastern Standard Time), Tue Sep ...

Filtering arrays of objects dynamically using Typescript

I am looking to create a dynamic filter for an array of objects where I can search every key's value without specifying the key itself. The goal is to return the matched objects, similar to how the angular material table filters all columns. [ { ...

Will not pass over if the number is already in the array?

Currently, I am developing a method to determine how many times a specific number appears in an array. Here is my method: public void freq(int[] arr) { Arrays.sort(arr); String output = ""; int count = 0; for (int i = 0; i ...

Sorting PHP arrays based on element relationships

Explaining this problem is a bit tricky, but essentially I have an array of items with IDs, some of which may contain a list of IDs for other items in the array. For example: $items = [ [id: 'one', deps: ['three']], [id: 'tw ...

AngularJS array modification log tracker

In my current situation, I want to bind a list of objects to an HTML table using AngularJS's two-way data binding. It's a straightforward scenario without anything too complex. I have a couple of questions: When monitoring changes in the mod ...

Deactivate and activate two buttons under the same condition (while entering information in forms) using Angular

Within my HTML form, there is a field labeled value. Alongside this field, there is an add button. When I click the add button, it duplicates the form field. My code is set up so that when I input a value (let's say 40) into the form field, then click ...

Troubleshooting TypeScript errors in Cassini with Google Chrome

While troubleshooting a .NET 4.6.1 web application with Cassini in Visual Studio 2015 version 14, update 3, I encountered an error on a page that utilizes TypeScript: Refused to execute script from 'http://localhost:53049/Scripts/app.ts' because ...

Extending an External Object with Custom Properties in TypeScript

When working with an external library, I often find myself needing to add new properties to passed-in parameters. Instead of using (<any>conv.data) due to the compiler error Object is of type 'unknown', I'm curious if there's a mo ...

What is the best way to retrieve the version hash of the current Angular PWA?

Is there a way to retrieve the currently active hash of my Angular PWA without waiting for an event trigger? While the SwUpdate object offers observables for accessing the hash when a new version is activated or becomes available, it does not seem to prov ...

How can I showcase Google images on my website?

I'm currently working on a project where I want to showcase images on my website retrieved from Google Images based on a keyword stored in an array. Here's the code I have so far: <?php $lines = file('things.txt'); echo $lines[arra ...

Advanced Layout: Angular Event window:scroll not Triggering

One issue I am facing is that the event gets triggered on some components but not others. For example, it fires as soon as I route to all other components except for the Landing component. Below are my code snippets: <-- Main Component --> <div c ...

Creating an array of objects using the NSArray class

As someone who is relatively new to Objective-C and iOS development, I've been experimenting with the Picker View feature. One interesting thing I did was define a Person Class that automatically assigns a name and age to each newly created Person obj ...