简体   繁体   中英

Compare object to class in typescript?

Is it possible in typescript to compare a given object to an interface or a class?

My first thought was to compare using typeof against an interface but this failed:

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();
}

I thought to convert the interface to a class and use instaceof but this also does not work:

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();
}

How can i validate the response object of an object from an API like this?

This cannot be the most efficient answer I am sure, but using this npm package and passing throwErrorOnAlien: true in the options i could successfully run jest with an api call and simply check the response body by passing in an expected map generated from an openapi/swagger definition (documentation driven development).

I is a shame though, i was hoping for a more elegant solution.

  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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM