theva theva - 1 year ago 116
TypeScript Question

Interfaces in TypeScript

I have some interfaces in my angular2 application. One of them is for the products that I fetch from a remote API.

My interface:

export interface Product {
id: number;
name: string;

When fetching products in my service I do something like this:

this.http.get(productsUrl).map(res => <Product>res.json());

And then this is subscribed somewhere in my app. What I just realized is that the products on the backend has a lot more attributes than just id and name, which is defined in my interface. I taught that this would raise some kind of error but it seems like my interface is just overwritten with whatever is fetched from the backend.

I can for instance get the price by doing product.price later in my application even if that was not part of my interface (but part of the product in the fetched json). Why is it so? What is the interface for if it's just overwritten anyway?

Answer Source

Interfaces in TypeScript are used for static type checking and auto-completion support in your IDE but they are removed at runtime. As usual in JS you can dynamically add and remove properties.

If you would cast the JSON to a class, the class also would only contain what was acquired from JSON but no implementation like methods.

See also How do I cast a JSON object to a typescript class

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