0

I have a very simple interface type as follows

export interface Amount {
    totalAmount: number;
}

And in my unit test I'm wanting to check the object returned from an API call is of this type but I'm nut sure how to do it. My API call is as follows:

const expectedResponse = {
    totalAmount: 5000
};

amountDataService
    .getAmountData(params)
    .subscribe(
        result => {
            expect(result instanceof Amount).toBe(true);
            expect(result).toEqual(expectedResponse);
        },
        error => {
            fail('Data was not returned successfully.');
        }
    );

However the line expect(result instanceof Amount).toBe(true); displays an error with the message:

'Amount' only refers to a type, but is being used as a value here

How can I check the type of the object returned?

atamata
  • 997
  • 3
  • 14
  • 32
  • Does this answer your question? [Interface type check with Typescript](https://stackoverflow.com/questions/14425568/interface-type-check-with-typescript) – R. Richards Jul 08 '20 at 18:55

1 Answers1

1

Dup of https://stackoverflow.com/a/31748606/390161

There is no way to runtime check an interface as type information is not translated in any way to the compiled JavaScript code.

You can check for a specific property or a method and decide what to do.

module MyModule {
  export interface IMyInterface {
      name: string;
      age: number;
  }
  export interface IMyInterfaceA extends IMyInterface {
      isWindowsUser: boolean;
  }
  export interface IMyInterfaceB extends IMyInterface {

  }

  export function doSomething(myValue: IMyInterface){
    // check for property
    if (myValue.hasOwnProperty('isWindowsUser')) {
      // do something cool
    }
  }
}
IAfanasov
  • 4,775
  • 3
  • 27
  • 42