代码之家  ›  专栏  ›  技术社区  ›  Dean Hiller

从typescript中对象中的数据创建类实例

  •  0
  • Dean Hiller  · 技术社区  · 4 年前

    我有一个 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 是因为某种原因出错了吗

    TS2739: Type '{ name: string; number: number; amount: string; due: string; }' is missing the following properties from type 'Invoice': _name, _number, _amount, _due
    
    1 回复  |  直到 4 年前
        1
  •  1
  •   jsejcksn    4 年前

    您示例中的代码是对 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);
    }