Here is an example of code I see way too often when people submit their code to our Angular certification exam:
While I could almost live with the above code, the following example makes me angry (especially because I tell people NOT to do that in bold uppercase characters in my instructions):
What’s the problem with that code? It uses any
, and any
is dangerous. It isn’t good because it turns off type safety. It makes your code less safe; it removes type information, it makes it less maintainable. It’s excruciating when we know that the HttpClient
is nice enough to let us specify the type of the data we’re going to get as a response:
Of course, this type of information does not guarantee that the server is going to return data of that shape, so we have to make sure the server is indeed returning that exact type of data.
But the thing is, once you add that type to your HTTP request, you can (should I say, you must) do the following:
And this is important because when you subscribe to that Observable, Typescript knows what kind of data you receive:
And that is why we use Typescript. Using the above syntax enables autocomplete in your IDE; it brings type safety so you can’t make typos. There are only benefits to using it.