Recently, I started learning Angular and I've been trying to wrap my head around how mapping from a response to an interface actually works.
Let's take a look at the API response I received:
[ {
"id": 2,
"name" : "Josh",
} ];
Here's what my TypeScript interface looks like:
export interface User {
name: string;
id: number | null;
}
In my service, I have a simple GET call:
getUser() {
return this.http.get<User>('http://localhost:4200/user/1').pipe(
map((response: User) =>
this.response = response,
));
}
In the component, I subscribe to this call:
callGetUser() {
this.getUser().subscribe((response: User) => {
this.user = response;
});
}
The 'user' object is also of type User:
user: User;
My expectation was to have a 'user' attribute of type User. I also thought there would be an error if the response attributes did not match the User interface - such as passing an "id2" attribute.
To test this, I created an instance of User in TypeScript:
https://i.sstatic.net/qX8Ki.png
https://i.sstatic.net/E3ast.png
Now, I'm left wondering why the mapping seems to work even when attributes don't match. Shouldn't I be getting an error? Is there a way to catch the mismatch and throw an error?