Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Create a class instance from data in an object in typescript

I have a full example on the typescript website. Basically, the last line in this function is not working

export function getInvoice(number: number): Invoice | undefined {
    let jsonObj = invoices.find(
        (invoice) => invoice.number === number
    );
    if(!jsonObj)
        return jsonObj;
    jsonObj = Object.assign(Invoice.prototype, jsonObj);
    return jsonObj;
}

Invoice is an array of objects including invoice data. After I get the object back, I am trying to convert it into a typed Invoice object to use. The return jsonObj is erroring out for some reason with the error

TS2739: Type '{ name: string; number: number; amount: string; due: string; }' is missing the following properties from type 'Invoice': _name, _number, _amount, _due

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The code in your example is a misuse of Object.assign(): if you want an instance of the Invoice class, then create one:

TS Playground

export function getInvoice(targetNumber: number): Invoice | undefined {
  const o = invoices.find(({number}) => number === targetNumber);
  if(!o) return undefined;
  const {amount, due, name, number} = o;
  return new Invoice(name, number, amount, due);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading