首页 > 解决方案 > 无法将严格为 false 的自由形式对象实体模型分配

问题描述

我有一个ordersConfirmation带参数的函数调用Orders[]。它在从存储库传递数组列表时起作用。

根据实体设置,我认为设置没有限制strict: false
但是,在构建单元测试时出现错误(见下文)。
如果我将参数更改为,则构建通过orders: any[]orders: Orders[]因为对象本身没有验证,但我认为这不是正确的方法。
有更好的方法还是我做错了?

功能:

export function ordersConfirmation(orders: Orders[]) {
  orders.forEach(function (order) {

  })
  return;
}

模型:

@model({settings: {strict: false}})
export class Orders extends Entity {
  @property({
    type: 'string',
    id: true,
    required: true,
  })
  _id: string;

  @property({
    type: 'number',
    required: true,
  })
  status: number;

  [prop: string]: any;

  constructor(data?: Partial<Orders>) {
    super(data);
  }
}

测试用例:

  it('ordersConfirmation() failed with error order', () => {
    const expectedError = new HttpErrors.Conflict('Error');
    const orders = [{
      _id: "5d635c090ac9bb4b4b3a86c7",
      status: 2,
    }];
    expect(() => ordersConfirmation(orders)).to.throw(expectedError);
  });

错误信息:

src/__tests__/unit/services.quote.unit.ts:46:37 - error TS2345: Argument of type '{ _id: string; status: number; }[]' is not assignable to parameter of type 'Orders[]'.
  Type '{ _id: string; status: number; }' is missing the following properties from type 'Orders': getId, getIdObject, toJSON, toObject

46     expect(() => ordersConfirmation(orders)).to.throw(expectedError);
                                       ~~~~~~

标签: typescriptloopbackloopback4

解决方案


这是数组Object

const orders = [{
    _id: "5d635c090ac9bb4b4b3a86c7",
    status: 2,
}];

这是数组Orders

const orders = [
    new Orders({
        _id: "5d635c090ac9bb4b4b3a86c7",
        status: 2,
    })
];


推荐阅读