HttpClient.get() responses.obj
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.