gyc gyc - 1 year ago 100
TypeScript Question

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": ""

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

private name: string;
private email: string;

constructor(name: string, email: string) { = name; = 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:


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?

Answer Source

The typescript compiler doesn't check your angular 2 template at all, so expression {{}} 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;

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download