angular 4 httpclient - type of http response object not enforced by interface

Viewed 1457

I have an API endpoint that returns the following response:

{
  "response": [ { "label": "mylabel", "name": "myname" } ],
  "status": 200
}

At first I created an interface that matches this exact structure, but then, just to test, I changed it to this:

export interface ListResponse {
    response: number;
    status: boolean;
}

this.http.get<ListResponse>('/api/list.php').subscribe(data => {
    console.log(data.response)
    console.log(data.status)
});

I was expecting to get a typescript error since the response clearly doesn't match the interface property types, but I was able to access the fields as usual. What about type safety, isn't it a problem?

1 Answers

Not in this case. Typescript at compiler time can not know if response from server will match interface you provide. So it can not throw exception. Response from server could actually be string or file. The only way to check this is at run time, when you actually get response from server. But at this point there is no TypeScript just plain JavaScript.

Edited:
The point of doing is, that you have type checking when processing result:

for (var o of data.response)

will work if in interface response is defined as array. If it is define as number, typescript will throw error. You will also have access to object o and its field label and name.

Related