TL;DR:
- An angular interface was defined and bound to
HttpClient.get()
responses.
- Responses were mapped to a seemingly generic
object
type.
- Attributes that weren't defined on the interface like
id
and title
were accessible on the response, as well as from .html called (eg. <p>Title is:
{{message?.title}}</p>
.
- If an interface is a contract, shouldn't it be preventing some of this?
New to Angular 4 from a Java background and stumbling on HttpClient
type safety. As this guide points out, one can pass an interface to http.get<>
to typecheck an HTTP response.
Consider a basic interface with a single foo
field:
export interface FooInterface{
foo: string;
}
Following the aforementioned guide, this interface can easily be bound to a response:
export class RestComponent {
message: FooInterface;
http.get<FooInterface>('/api/items').subscribe(data => {
this.message = data;
console.log(this.message);
console.log(typeof(this.message));
console.log(this.message.foo);
});
At this point, I hit a random API which does not have a foo
field. The actual API has two fields: id and title. To my surprise, when I hit this API, the data object was still created:
Data is a generic object with fields id
and title
. A call to data.foo
return undefined
.
Furthermore, while the interface prevents me from accessing these id and title fields directly, they are still available through calls like data['id']
. They can also be referenced in the HTML.
<h1>
id: {{message.id}}
<br>
title: {{message?.title}}
</h1>
And this gets rendered! In fact, the only thing the interface seems to do is prevent me from doing something like:
`this.message.title`
That's cool I guess... but if these fields can be accessed via this.message['title']
or reference in html files, then what's the point of the interface?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…