HttpClient type safety seems to ignore interface

前端 未结 1 1362
感情败类
感情败类 2020-12-07 04:17

TL;DR:

  1. An angular interface was defined and bound to HttpClient.get() responses.
  2. Responses were mapped to a seemingly generic obj
相关标签:
1条回答
  • 2020-12-07 04:32

    When comming from a Java background, the generic problem with TypeScript typing is that types are not enforced. Whenever you do a cast in TypeScript, no runtime exception is thrown if the object is not of that class. The exception is thrown later when accessing the missing fields of that object.

    What you want to do is not compile time type checking (as TypeScript does) but you want to enforce a specific type of the response.

    You can do this by checking the response manually:

        http.get<FooInterface>('/api/items').subscribe(data => {
            if (typeof data !== 'object')
              throw new Error('Expected an object')
            if (typeof data.foo !== 'string')
              throw new Error('Expected a string property')
            this.message = data;
        });
    

    If you want to automate this, have a look at JSON Schema validation. You need to define a JSON schema in addition to your TypeScript class. There is a library that will help you keep them in sync. There are also libraries that can automatically generate them from e.g. Spring REST endpoints, so you can keep them in sync with your backend services.

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