Home > Software design >  Create a class instance from data in an object in typescript
Create a class instance from data in an object in typescript

Time:02-28

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

CodePudding user response:

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);
}
  • Related