gyc
gyc

Reputation: 4360

Class member of type Object with http service 'as' syntax

I have an API that returns:

{
    "results": [{
        "name": {
            "title": "mr",
            "first": "konsta",
            "last": "tuomala"
        },
        "email": "[email protected]"
        ...

I'm trying to map a typescript class to this model like so:

private name: string;
private email: string;

constructor(name: string, email: string) {
    this.name = name;
    this.email = email;
}

I can map email as a string but what about name?

Now in my service I do this;

return this.http.get('API').toPromise().then(
  response => response.json().results as User[]
)

It automatically maps the name object to a User member and I can access it like so in the template:

{{user.name.first}}

How come there is no error trying to map an object to a string?

What is the right way to handle this kind of data? Do I have to create a Name class and use it as a type for the name member of the User class?

Upvotes: 0

Views: 209

Answers (2)

slaesh
slaesh

Reputation: 16917

Seems fine. But your variable private Name: string shouldnt be from type string! It's an object.. so declare it as any or as type of Name and define that class too.

Remember using cast or as will only work with properties but there won't be any functions available from that class..

Upvotes: 1

Petr Adam
Petr Adam

Reputation: 1437

The typescript compiler doesn't check your angular 2 template at all, so expression {{user.name.first}} just waits to be executed at runtime. If you would put this code directly into your Component class code, you would surely be notified.

Type checking is not done in transpiled executed javascript, you receive no error. It's like with typescript interfaces, it just disappears during compilation.

The best what you can do, is to create the type for Name (e.g. MyName) with properties title, first, last and set it instead of string private Name: MyName;

Upvotes: 1

Related Questions