将对象与打字稿中的类进行比较?

时间:2019-09-22 09:22:33

标签: typescript interface

在打字稿中是否可以将给定的对象与接口或类进行比较?

我的第一个想法是将typeof与接口进行比较,但这失败了:

interface EmployeeModel {
  id?: string,
  employee_name?: string,
  employee_salary?: string,
  employee_age?: string,
  profile_image?: string,
}
const employee = response.body.pop();
if (typeof employee === EmployeeModel) {
  next();
}

我想将接口转换为类并使用instaceof,但这也不起作用:

class EmployeeModel {
  id?: string;
  employee_name?: string;
  employee_salary?: string;
  employee_age?: string;
  profile_image?: string;
}
const employee = response.body.pop();
if (employee instanceof EmployeeModel) {
  next();
}

如何从这样的API验证对象的响应对象?

1 个答案:

答案 0 :(得分:0)

我肯定这不是最有效的答案,但是使用此npm包并在选项中传递throwErrorOnAlien: true可以使我成功地通过api调用运行笑话,并通过传递期望的映射来简单地检查响应主体从openapi / swagger定义(文档驱动的开发)生成。

尽管我很遗憾,但我希望有一个更优雅的解决方案。

  it('Check body response', next => {
    try {
      objectReduceByMap(
        response.body,
        EmployeesService.employeeGetResponseFormat,
        { throwErrorOnAlien: true }
      );
      next();
    } catch (e) {
      // objectReduceByMap threw an error so alien attributes were discovered in the api response.
      // Calling next with the error so Jest stops.
      next(e);
    }
  });

https://github.com/acrontum/openapi-nodegen-typescript-api-test-rig/blob/master/README.md

相关问题