Utilize a string to access and sort the properties of a class in TypeScript

Let's discuss a simple problem involving objects in Javascript. Take for example an object like this:

var obj={
    par1:'value1',
    par2:'value2'
}

In JavaScript, we can access the values like obj['par1']. Now, the question is, can we do something similar in TypeScript with a class structure like this:

export class obj{
    par1:string;
    par2:string;
}

this.obj['par1']=value1

Update

Introducing the Documents class

export class Documents {
    par1: string
    par2: string
    constructor(par1: string,
        par2: string
    ){
        this.par1=par1
        this.par2=par2
    }
}

Here is my attempt at solving the problem:

private docs:Documents[]=new Documents[
    new Documents('value1','value2'),
    new Documents('value3','value4')
];
sort(ordertype:string,property:string){
    for(let doc of this.docs){
        for(let field in doc)
            console.log(doc[field])
    }
}

Encountered an error:

[ts] Element implicitly has an 'any' type because index expression is not of type 'number'.

I have attempted to cast it to a string but without success.

Update 2

Error identified and corrected. The code above is now functioning correctly.

Answer №1

Ensure the Documents array is properly initialized by following this structure:

let docs: Documents[] = [];
docs.push(new Documents('value1', 'value2'));
docs.push(new Documents('value3', 'value4'));

Alternatively, you can use the following syntax:

let docs: Documents[] = [new Documents('value1', 'value2'), new Documents('value3', 'value4')];

If you implement these changes, your code should function correctly. You can test it out in the playground.

Answer №2

Experience the difference by swapping out alert(obj[key]) for alert((obj as any)[key])

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

Customizing AxiosRequestConfig with Axios in TypeScript can greatly enhance the functionality and

Currently working with React and Axios. Lately, I've been experimenting with custom configurations in Axios as shown below: import $axios from 'helpers/axiosInstance' $axios.get('/customers', { handlerEnabled: false }) However, wh ...

Increase the size of the NativeScript switch component

Here is the code I am working with: .HTML <Switch style="margin-top: 10" (checkedChange)="onFirstChecked1($event)" row="0" col="1" horizontalAlignment="center" class="m-15 firstSwitchStyle"></Switch> .CSS .firstSwitchStyle{ width: 30%; ...

Angular 4 allows for dynamically applying the active class to a clicked button, enhancing interactivity

Issue: <button *ngFor="let button of buttons" [ngClass]="{'active': isClicked}" (click)="isClicked = !isClicked" Description: A total of 10 buttons are displayed on the screen. When I click on button number 1, each button receives the clas ...

Tips for resolving type inference for a component variable in a jest Mount test created using reactjs

I am currently working on a React project that is built in Typescript, specifically dealing with a unit test involving the use of mount from Enzyme. As I strive to align the project with the tsconfig parameter "noImplicitAny": true, I am faced with the cha ...

Standards for coding across different languages

As I work on developing a framework that accommodates both C# and TypeScript, I am faced with an interesting dilemma. Take, for instance, the Validator class in C#: class Validator { public bool Validate(string value) { return someConditi ...

Can you explain how to utilize prop values for setting attributes in styled-components v4 with TypeScript?

Overview Situation: const Link = styled.a` border: solid 1px black; border-radius: 5px; padding: 5px; margin: 10px 5px; `; type ButtonProps = React.ButtonHTMLAttributes<HTMLButtonElement>; const LinkAsButton = styled(Link).attrs<ButtonP ...

Guide on converting a JSON object into a TypeScript Object

I'm currently having issues converting my JSON Object into a TypeScript class with matching attributes. Can someone help me identify what I'm doing wrong? Employee Class export class Employee{ firstname: string; lastname: string; bi ...

Issue encountered during mozjpeg installation - unable to locate mozjpeg's cjpeg in the vendor directory due to

During my attempt to set up mozjpeg within a Docker container running NAME="Alpine Linux" ID=alpine VERSION_ID=3.11.7 PRETTY_NAME="Alpine Linux v3.11" HOME_URL="https://alpinelinux.org/" BUG_REPORT_URL="https://bugs.alpin ...

Tips for customizing the appearance of date and time formats

Does anyone know how to retrieve this specific time format using Angular2 TypeScript? 2016-9-25T05:10:04.106Z I've tried searching online but couldn't find a straightforward solution. When attempting this in TypeScript, the following results a ...

When attempting to access http://localhost:3000/traceur in Angular 2 with the angular-in-memory-web-api, a 404 (Not Found) error

Hello, I'm encountering an issue with angular-in-memory-web-api. I have attempted to use angular2-in-memory-web-api in SystemJS and other solutions, but without success. I am currently using the official quickstart template. Thank you for any assistan ...

Typescript throwing error TS2307 when attempting to deploy a NodeJS app on Heroku platform

Encountering an error when running the command git push heroku master? The build step flags an error, even though locally, using identical NodeJS and NPM versions, no such issue arises. All automated tests pass successfully without any errors. How can this ...

Steps to show the chosen index value in an alert pop-up using Ionic 2 framework

I'm in the process of trying to showcase a selected index value within an Ionic 2 alert box. However, I'm struggling to find the correct method to display it in the Ionic prompt. This pertains to the home.ts import { Component } from '@ang ...

Issue: Unable to locate a matching object '[object Object]' of type 'object'. NgFor can solely bind to data structures like Arrays and Iterables

I am facing an error that says "Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays." I am trying to create a Notification list but I can't figure out w ...

Incorporating CodeMirror into Angular2 using TypeScript

I've been working on integrating a CodeMirror editor into an Angular2 project, but I'm encountering some issues with the instantiation of the editor. Here is my code snippet: editor.component.ts import {Component} from 'angular2/core' ...

What is the reason behind the mandatory credentials option for the CredentialsProvider?

When using NextAuth.js with a custom sign in page, some code examples for the credentials provider do not include the credentials option in the CredentialsProvider. According to the documentation (here), the credentials option is meant to automatically "ge ...

Tips for presenting a quiz in a random order and preventing duplicate questions in a React Native app

Hello everyone, I am working on creating a Quiz app in React Native that displays questions randomly without any duplication. So far, I have managed to display the Quiz questions randomly, but I'm stuck on preventing duplicates. This is a new learning ...

Angular2 - how can I effectively organize the logic between my components and services?

Within my current project setup, I have the following structure implemented: I have a Component that interacts with a Service Class which in turn calls an external API. The specific logic that I need to implement is related solely to the user interface. ...

Substitute a value in a list with a distinctive identification code

I have a list of dailyEntries. Each entry has a unique identifier called id. I am given an external dailyEntry that I want to use to replace the existing one in the array. To achieve this, I can use the following code: this.dailyEntries = this.dailyEntri ...

Show the attribute of an element in a pop-up window

I have a modal from ngx-bootstrap that I want to display in there a property of my object let's say the name: public students = [ { id: 1, name: 'lorem'} In this button that is common for all entries in the table (each row has this butt ...

The module for the class could not be identified during the ng build process when using the --

Encountering an error when running: ng build --prod However, ng build works without any issues. Despite searching for solutions on Stack Overflow, none of them resolved the problem. Error: ng build --prod Cannot determine the module for class X! ...