0

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?

rablentain
  • 6,641
  • 13
  • 50
  • 91

2 Answers2

2

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

Community
  • 1
  • 1
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
2

Interface in TypeScript "...is a powerful way of defining contracts...". It's only a contract, declaration - what properties are expected to be implemented in an object. Then you cast "any" object to an interface, you don not modify this object, you just tell transpiler, that you are expecting existance of certain properties in it.

TSV
  • 7,538
  • 1
  • 29
  • 37