Use cases

There are actually quite a few valid use cases to consider for runtime type checks.

For instance, when the service layer of our WorldExplorer application makes calls to the REST API, it will get the data back as JSON. Once we get hold of the corresponding JSON, we will need to extract information from it in order to create instances of our own domain model types. Doing so requires attention to avoid runtime type safety issues.

One problem with web APIs is that their implementation can change over time. At some point, some fields that we expect to be present might be renamed or even disappear. APIs should, of course, be versioned, but theory and reality don't always agree. In addition, we might also make spelling mistakes on our side (for example, using an invalid name for a property).

On its own, the TypeScript compiler can't know for sure that the API responses will have the shape that we expect, that fields will have the expected types, and many more things.

The question when there are issues at runtime is: how will our code react? Will it fail in a predictable way or not? If not, then we risk impacting the users of our applications, which is far from ideal.

To avoid such pitfalls, we need to be able to validate that fields are present, with correct names and the expected types.

Here are a few additional use cases to consider:

  • Sometimes, fields are optional and will not necessarily be present; how do we handle that?
  • We might not want to create a one-to-one mapping between the structure of API responses and our own data model.
  • We might want to perform transformations.
  • We might want to fetch additional information to enrich our representation.

We would certainly benefit from having the possibility to perform runtime type checks and validations, as well as conversions without compromising type safety at runtime. This would enable us to react appropriately in the event of errors, thus failing faster if needed.

Now that you understand why having type safety at runtime is beneficial, let's discover a library that we can use to achieve precisely that.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.190.217.134