Angular2 cast a json result to an interface

后端 未结 2 918
不知归路
不知归路 2020-12-15 17:53

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

相关标签:
2条回答
  • 2020-12-15 18:26

    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:

    • If you know the data coming from the api is the correct shape, and you are just looking to give your IDE / the compiler information about this shape, you can cast as per toskv's answer.
    • If you are not sure of the api and want your app to throw if the data is the wrong shape, you are going to have to implement your own check. This is a bit of overhead but it's well worth it for larger apps.

    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.

    0 讨论(0)
  • 2020-12-15 18:27

    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.

    0 讨论(0)
提交回复
热议问题