我有一个 full example 在typescript网站上。基本上,这个函数的最后一行不起作用
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; }
发票是一个包含发票数据的对象数组。取回对象后,我试图将其转换为要使用的类型发票对象。回归 jsonObj 是因为某种原因出错了吗
jsonObj
TS2739: Type '{ name: string; number: number; amount: string; due: string; }' is missing the following properties from type 'Invoice': _name, _number, _amount, _due
您示例中的代码是对 Object.assign() :如果您想要 Invoice 类,然后创建一个:
Object.assign()
Invoice
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); }