Reputation: 93
I am new in angular and I am trying to understand how the mapping from a response into an interface works.
I have following API response:
[ {
"id": 2,
"name" : "Josh",
} ];
and my TS interface looks like this:
export interface User {
name: string;
id: number | null;
}
I make a simple get call in the service:
getUser() {
return this.http.get<User>('http://localhost:4200/user/1').pipe(
map((response: User) =>
this.response = response,
));
}
And subscribe in the component:
callGetUser() {
this.getUser().subscribe((response: User) => {
this.user = response;
});
}
My user is also from type User:
user: User;
That I expect is that I get a user attribute of type User. I would also expect an error if the attributes from the response are not matching the attributes from the User interface - e.g I pass an "id2"-attribute , see pics below.
This is the case is simply define an User-instance in TS:
My question is why is the mapping working even when the attributes are not matching? Should't I get an error? Is there a way to get an error if so?
Upvotes: 0
Views: 489
Reputation: 1109
You have to remember that Typescript will be compiled into Javascript before being execute. Javascript has no kind of type checking, so when you write
getUser() {
return this.http.get<User>('http://localhost:4200/user/1').pipe(
map((response: User) =>
this.response = response,
));
}
you're saying that you're sure that the http request will return an Object with the same structure as User. The problem is that during runtime (when the call is actually performed), there will be no type checking, cause the browser is reading Javascript, not Typescript. The only way you could check the consistency of an object is to check if it has all the properties. So if User has an id and a name you could change your map like this:
return this.http.get<User>('http://localhost:4200/user/1').pipe(
map((response: User) =>
if(response.id && response.name)
this.response = response;
else
console.log('This is not a user!');
));
}
Upvotes: 2