Using Angular2 and typescript, I have JSON returned from a webApi and I need to get it into an array of a certain type. I can\'t figure out how to cast the json to the inte
Viktor Savkin has a library to do runtime checking of types for this sort of situation but it doesn't work with interfaces because Typescript doesn't export runtime information on interfaces. There is a discussion about this here.
There are two possible solutions:
In general I see Typescript's types as compiler hints more than a rigorous type system - it has to compile down to an untyped language after all.
You can do a type assertion to the interface you are expecting on the object created by JSON.parse.
this.http.get('http://localhost:4200/').subscribe((value: Response) => {
let hero = <ServerInfo>value.json();
});
However this will not result in any errors if the server sends you bad objects because of 2 reasons.
At compile time the transpiler does not know what the server will send.
At runtime all type information is erased since everything gets compiled to javascript.