Exploring cartography in Typescript

I'm struggling a bit with working on maps in Typescript. My goal is to use a HashMap similar to what's available in Java. For example, here is an example of my Java object:

public class Payment {
    private String id;
    private DateTime created;

    //when they actually received the payment
    private DateTime paidDate;
    private String customerId;
    private String companyId;
    private BigDecimal amount;
    private BigDecimal allocated;
    private String description;

    // it must be the Id of PaymentMethod
    private String type;

    //to improve it
    private String currency;

    private Boolean fullPaid = false;
    private Boolean lockArchive = false;

    //<InvoiceId, Amount>
    private HashMap<String, BigDecimal> invoices = new HashMap<>();

    //getter and setters....

In Typescript, I've attempted to create a similar class. Here's an example:


export class Payment {
  public id?:string;
  public created?:string;
  public paid_date?:Date;
  public customer_id?:string;
  public company_id?:string;
  public amount?:number;
  public allocated?:number;
  public description?:string;
  public type?:string;
  public currency?:string;
  public full_paid?:boolean;
  public lock_archive?:boolean;
  public invoices:  {[invoice_id:string]:number};


  constructor(id: string, created: string, paid_date: Date, customer_id: string, company_id: string, amount: number, allocated: number, description: string, type: string, currency: string, full_paid: boolean, lock_archive: boolean, invoices: { [p: string]: number }) {
    this.id = id;
    this.created = created;
    this.paid_date = paid_date;
    this.customer_id = customer_id;
    this.company_id = company_id;
    this.amount = amount;
    this.allocated = allocated;
    this.description = description;
    this.type = type;
    this.currency = currency;
    this.full_paid = full_paid;
    this.lock_archive = lock_archive;
    this.invoices = invoices;
  }
}

I'm trying to add to the 'invoices' map. Here's the function I have:


  public invoicesMap = new Map<string, number>();

  constructor(public dialogRef: MdDialogRef<PaymentInvoiceSelectDialogComponent>,
              private customerService:CustomerService,
              private paymentServices: PaymentsService) {

  }

  ngOnInit() {
    // Implementation details omitted for brevity.
  }

  selectedInvoice(invoiceId: string, amount: number, event:any) {
    // Implementation details omitted for brevity.
  }


  savePayment(){
    console.log(JSON.stringify(this.payment));
    // Implementation details omitted for brevity.
  }

The items are successfully added to the 'invoiceMap,' but now I am facing challenges adding 'invoiceMap' to 'payment.invoices.' Any guidance on how to proceed would be greatly appreciated. Thank you.

Answer №1

If you want to convert it into a Map within the context of Payment, you can do so by following this example:

public invoices: Map<string, number>;

After defining the map, you can either directly assign the existing map values or transform them into an object similar to what is used in Payment:

let m = new Map<string, number>();

let m2 = {} as { [key: string]: number };
m.forEach((value, key) => m2[key] = value);

Answer №2

If you plan on using String as keys, a hashmap may not be necessary since every object in javascript, including typescript, functions as a basic map. The Map class is typically only needed when an alternative to a String is required as a key.

For more information on JavaScript hash maps, check out this question -> How is a JavaScript hash map implemented?

Answer №3

To keep things simple, consider using the Record type Record<string, any>

const dataMap : Record<string, any> 

This will create a type that can store any string keys and values. It's ideal for cases where you are unsure of the keys beforehand.

Another option to explore is the Partial type, which allows for partial object definitions.

For more information on utility types in TypeScript, check out this link

Answer №4

For those looking to convert C# class into TypeScript, TypeLite is a handy tool that can help you achieve this: . This addon seamlessly converts any C# class into a TypeScript class.

Prior to initiating async communication, ensure to parse the request to JSON. In your code behind or controller, respond with your object serialized into JSON format.

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

The error message "JApplet java.lang.NoClassDefFoundError: org/json/JSONException" indicates that

Recently, I encountered an issue while trying to open a JApplet jar file on the internet. Each time I attempted to access it, an error message popped up: java.lang.NoClassDefFoundError: org/json/JSONException I diligently searched for solutions to this ...

What can you do with jQuery and an array or JSON data

Imagine having the following array: [{k:2, v:"Stack"}, {k:5, v:"Over"}, , {k:9, v:"flow"}] Is there a way to select elements based on certain criteria without using a traditional for/foreach loop? For example, can I select all keys with values less than ...

Creating a dynamic PageFactory WebElement with placeholder symbols

In my scenario, I am generating locators dynamically based on the element chosen from a list. For example, here is a sample generated ID: Function:TableName:0:submenuAction The number 0 represents the counter, indicating the selection of the first eleme ...

Include some text before and after the bar element

I am attempting to insert text preceding and succeeding the bar, as depicted in the image below. <div class="container"> <div class="progress progress-info progress-striped"> <div id="storage-component" class="bar" style="wi ...

Angular material checkbox showing incorrect behavior when in an indeterminate state

I am currently using Angular 7 along with Angular Material 7.3.7, and I am facing an issue while trying to create an unordered list of mat-checkbox. The problem I am encountering is that the indeterminate state is not consistently displayed as expected. Be ...

Retrieve items from the type group [T, V] where U is not included, and [U, any]. T should be a union type in the context

Some time ago, I shared my query on Inferring the shape of the result from Object.fromEntries() in TypeScript. The response I received seemed to work well for me until a couple of days back. declare global { interface ObjectConstructor { fromEntries& ...

Guide on redirecting to another webpage after submitting a Django form and securely saving form data to the backend database

Objective: Ensure that data submitted through a Django form is successfully saved on the admin side. Issue: Although able to redirect to another page after submitting the form, the data does not get saved on the admin side. How can I resolve this using ei ...

Refresh the source dropdown when the x-editable is shown

I need to update the source data for x-editable just before it is displayed in order to ensure that my dropdown menu always displays the most recent entries, even if the source has changed. For more information, you can visit: http://jsfiddle.net/XN7np/3/ ...

Unable to access and control HTML elements using JavaScript

let button = document.getElementsByTagName('button'); button.value = 8; //button.textCont = 'X'; --- DOESN'T WORK. //button.innerHTML = 'X'; --- DOESN'T WORK. body { ...

Exploring the benefits of utilizing useState and localStorage in Next.js with server-side

Encountering an error consistently in the code snippet below: "localstorage is not defined" It seems like this issue arises because next.js attempts to render the page on the server. I made an attempt to place the const [advancedMode, setAdvanced ...

When executed with gulp, Typescript generates an error saying "Trying to access the 'length' property of an undefined value."

While attempting to develop a project in Gulp that incorporates Typescript, I encountered an error when running npm run gulp. The error message indicates: [09:03:17] Using gulpfile ~/Programming/Projects/ghars/gulpfile.js [09:03:17] Starting 'default ...

Using an empty filter string with filterPredicate in Angular Material Table

I need assistance in getting the filterPredicate to function properly when dealing with an empty filter string. Here is the HTML code: <mat-form-field> <mat-label>Filter</mat-label> <input matInput (keyup)="applyFilter($e ...

SQL stores Array Input as a static identifier 'Array'

Previously, I was able to save an object in the database. However, now I need to save each individual data in an array within a row. I attempted to use array_column to store a specific set of data in a column, but it ended up saving as the word 'Array ...

Encountering a type error with React component children in TypeScript

A few days ago, I delved into learning React with TypeScript and encountered the following error: /home/sotiris/Github/ecommerce-merng-platform/admin/src/components/DashboardHOC/DashboardHOC.tsx TypeScript error in /home/sotiris/Github/ecommerce-merng- ...

Perform a single click and a double click on an anchor element in the document

I am attempting to implement two actions when a user clicks on an anchor tag. The anchor tag will contain a video link. My goal is for the URL to open in a new window when the user single-clicks on the anchor tag, and for the use of the HTML5 download attr ...

Execute a script upon page load

Is there a way to trigger a script tag <script> immediately upon the website loading? I've experimented with various codes, but haven't found one that meets my needs. ...

What exactly defines the nature of a type?

Have you ever wondered about the nature of a type? All this talk may seem perplexing, but sometimes code speaks louder than words. // Consider an interface interface A { } // Now, imagine a class that implements this interface. // There are several impl ...

Angular HTTP Requests: Using Headers to Communicate with NodeJS API

I am facing an issue with sending headers in my HTTPS requests using my Angular application. I need to include a Token to authorize the requests in my NodeJS API backend, where every route is validated. Upon examining the request headers: host: 'loc ...

Array containing various types of data arranged in a two-dimensional structure

I'm looking to build a two-dimensional array to store database records. For example, the first element would be an int and the second element a String (representing columns in the database). What's the best way to go about this? Is using an array ...

Technique for seamlessly moving between subpages and main page while scrolling to a specific id

I'm struggling with coding and thought I'd reach out for help here. Can anyone provide a solution to my problem? Issue - I have a navigation link on my main page that scrolls to an ID using jQuery. It works fine on the main page, but not on any ...