4

I am having a bit of trouble working with maps int Typescript. What I am trying to do is to use a HashMap smilier to that found in Java for example here is 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....

So what I have done in Typescript it to create a similar class for 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 am trying to to basically add to the the invoices map so I have the following function,

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

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

  }

  ngOnInit() {

    this.customer.subscribe((res)=>{
      this.customer_name = res.customer_name
    }, error=>{
      console.error(<any>error);
    });

    this.customerService.getListOfCustomerInvoices(this.customerId,'0','25')
      .subscribe( (res) =>{
       this.invoices = res;
      },
      error => {
        console.error(<any>error);
      });

  }

  selectedInvoice(invoiceId: string, amount: number, event:any) {

    if(event.checked){

      if(!_.isEmpty(this.payment.invoices)){

        for(let [key, value] of this.invoicesMap) {

          if (key !== invoiceId) {

            this.invoicesMap.set(invoiceId, amount);

            for(let [key, vvalue] of this.invoicesMap) {

              if (key === invoiceId) {

                this.availableAllocation = this.availableAllocation - vvalue;

              }
            }
          }
        }
      } else {

        this.invoicesMap.set(invoiceId,amount);

        for(let [key, vvalue] of this.invoicesMap) {
          if(key === invoiceId){
            this.availableAllocation = this.amount - vvalue;
          }
        }
      }
    } else if(!event.checked){

      for(let [key, vvalue] of this.invoicesMap) {

        if (key === invoiceId) {

          console.log("removing an item");
          this.availableAllocation += vvalue;
        }

      }
    }

    //at this point I would like to set this.payment.invoices to this.invoiceMap
    for(let [key, value] of this.invoicesMap){
      let v = {invoice_id:key,amount:value};
      console.log(v);
    }

    this.payment.allocated = this.availableAllocation;
  }


  savePayment(){
    console.log(JSON.stringify(this.payment));
    // this.paymentServices.updatePayment(this.payment)
    //   .subscribe((res)=>{
    //     this.payment = res;
    //     this.dialogRef.close(this.payment);
    //     },
    //     error =>{
    //       console.log(<any>error);
    //     });
  }

the items are added to the invoiceMap but the problem I am having now is adding invoiceMap to payment.invoices. If someone can point me in the right direction that would be much appreciated. Thanks

Nitzan Tomer
  • 155,636
  • 47
  • 315
  • 299
Limpep
  • 499
  • 3
  • 11
  • 22

4 Answers4

5

You can change it to a Map in Payment as well:

public invoices: Map<string, number>;

And then you can simply assign the map that you have.
Or you can iterate over the map entries and turn them into an object like you have in Payment:

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

let m2 = {} as { [key: string]: number };
m.forEach((value, key) => m2[key] = value);
Nitzan Tomer
  • 155,636
  • 47
  • 315
  • 299
  • I changed invoices to map in payment and like you said to iterate over the map and its working as expected, Thanks for your help. – Limpep May 31 '17 at 14:20
2

If you are gonna use String as keys there is no reason to use a hashmap, every object in javascript, as well as typescript, is a simple map. The only reason you would need to use the Map class is if you need something other than a String as a key.

Please take a look at this question -> How is a JavaScript hash map implemented?

Eduardo Vargas
  • 8,752
  • 2
  • 20
  • 27
1

The most simple way is to use Record type Record<string, any>

const invoicesMap : Record<string, any> 

This would allow you to have a type with any any string and values. Only use it if you don't know the keys in advance.

You can also look at Partial type. If you have some values but not all.

https://www.typescriptlang.org/docs/handbook/utility-types.html

aWebDeveloper
  • 36,687
  • 39
  • 170
  • 242
0

if I understand what do you want you can use TypeLite : http://type.litesolutions.net/ this addon convert any class c# in typescript class.

before the async comunication you parse the request to json and into your code behind( or into controller )you response with your object serialized into json.

C.Fasolin
  • 313
  • 1
  • 4
  • 19
  • Thanks but I am using Java, plus i could use this https://github.com/vojtechhabarta/typescript-generator. – Limpep Jun 01 '17 at 16:38